This time I will bring younode.jsHow to implement the decorator pattern, what are theprecautionsfor implementing the decorator pattern in node.js, the following are practical cases , let’s take a look.
The implementation of the decorator pattern emphasizes the combination of classes rather thaninheritance. This increases flexibility. In node.js, this can be achieved through the call function. The call function can call a member function of another class in anobject, in this sense, the purpose of class combination is achieved.
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());
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
node.js implements the encapsulation of the WeChat interface
JS implements news display at the bottom with sliding effects
The above is the detailed content of How to implement the decorator pattern in node.js. For more information, please follow other related articles on the PHP Chinese website!