這篇文章主要介紹了node.js實現的裝飾者模式,簡單說明了裝飾者模式的原理、功能並結合實例形式給出了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());
以上是node.js裝飾者模式介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!