当前位置: 移动技术网 > IT编程>开发语言>JavaScript > node.js实现的装饰者模式示例

node.js实现的装饰者模式示例

2017年09月07日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网