這次帶給大家node.js如何實作裝飾者模式,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());
我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是node.js如何實作裝飾者模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!