最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
node.js实现装饰者模式分享
时间:2017-09-07 编辑:简简单单 来源:一聚教程网
node.js作为一个Javascript运行环境,它带来的效果也是有着其独特之处的,这次文章为大家带来了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脚手架开发解析 12-04
- node 利用进程通信实现Cluster共享内存 11-22
- node通过npm写一个cli命令行工具 10-15
- Node.js中使用mongoose操作mongodb数据库的方法 09-25
- nodejs对express中next使用详解 09-10
- node.js实现微信JS-API封装接口 09-08