Home  >  Article  >  Web Front-end  >  How to implement the decorator pattern in node.js

How to implement the decorator pattern in node.js

php中世界最好的语言
php中世界最好的语言Original
2018-04-18 13:40:351381browse

This time I will bring you node.jsHow to implement the decorator pattern, what are the precautions for 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 than inheritance. 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 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());

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn