Home > Article > Web Front-end > Introduction to node.js decorator pattern
This article mainly introduces the decorator pattern implemented by node.js, briefly explains the principle and function of the decorator pattern, and provides the implementation method of the node.js decorator pattern in the form of examples. Friends in need can refer to it. Next
The examples in this article describe the decorator pattern implemented by node.js. Share it with everyone for your reference, the details are as follows:
The implementation of the decorator pattern emphasizes the combination of classes rather than inheritance. This increases flexibility. In node.js, this can be achieved through the call function. The call function can call the member function of another class in an object, 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());
The above is the detailed content of Introduction to node.js decorator pattern. For more information, please follow other related articles on the PHP Chinese website!