欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-03 19:37:48
本文实例讲述了node.js实现的装饰者模式。分享给大家供大家参考,具体如下: 装饰者模式的实现更强调类的组合而不是通过继承。这样可以增强灵活性。在node.js 中,可...

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