本文實例講述了node.js實現的裝飾者模式。分享給大家供大家參考,具體如下:
裝飾者模式的實現更強調類的組合而不是通過繼承。這樣可以增強靈活性。在node.js 中,可以通過call函數實現。call函數可以在一個對象中調用另一個類的成員函數,從這種意義上達成類的組合目的。
var util = require('util');var Beverage = function(){ var description = "Unkown Beverage" this.getDescription = function(){ return description; }}function Espresso(){ Beverage.call(this); this.description = "Espresso";}util.inherits(Espresso, Beverage);Espresso.prototype.cost = function(){ return 1.99;}function HouseBlend(){ Beverage.call(this); this.description = "House Blend Coffee";}util.inherits(HouseBlend, Beverage);HouseBlend.prototype.cost = function(){ return .89;}function Mocha(beverage){ this.beverage = beverage;};Mocha.prototype.getDescription = function(){ return this.beverage.getDescription() + ", Mocha";}Mocha.prototype.cost = function(){ return 0.20 + this.beverage.cost();}function Whip(beverage){ this.beverage = beverage;};Whip.prototype.getDescription = function(){ return this.beverage.getDescription() + ", Whip";}Whip.prototype.cost = function(){ return 0.40 + this.beverage.cost();}var beverage = new Espresso();console.log(beverage.getDescription() + " $" + beverage.cost());var beverage2 = new HouseBlend();beverage2 = new Mocha(beverage2);beverage2 = new Mocha(beverage2);beverage2 = new Whip(beverage2);console.log(beverage2.getDescription() + " $" + beverage2.cost());希望本文所述對大家node.js程序設計有所幫助。
|
新聞熱點
疑難解答