您好,登錄后才能下訂單哦!
本文實例講述了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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。