本文實(shí)例講述了node.js實(shí)現(xiàn)的裝飾者模式。分享給大家供大家參考,具體如下:
裝飾者模式的實(shí)現(xiàn)更強(qiáng)調(diào)類的組合而不是通過(guò)繼承。這樣可以增強(qiáng)靈活性。在node.js 中,可以通過(guò)call函數(shù)實(shí)現(xiàn)。call函數(shù)可以在一個(gè)對(duì)象中調(diào)用另一個(gè)類的成員函數(shù),從這種意義上達(dá)成類的組合目的。
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());希望本文所述對(duì)大家node.js程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注