1、特点
装饰者模式可以动态地给某个对象添加一些额外的职责,而不会影响从这个类中派生的其他对象。
2、demo
var Plane = function() {}
Plane.prototype.fire = function() {
console.log('发射普通子弹');
}
var MissileDecorator = function(plane) {
this.plane = plane;
}
MissileDecorator.prototype.fire = function() {
this.plane.fire();
console.log('发射导弹');
}
var AtomDecorator = function(plane) {
this.plane = plane;
}
AtomDecorator.prototype.fire = function() {
this.plane.fire();
console.log('发射原子弹');
}
var plane = new Plane();
plane = new MissileDecorator(plane);
plane = new AtomDecorator(plane);
plane.fire();
// 分别输出: 发射普通子弹、发射导弹、发射原子弹
参考文献:《JavaScript设计模式与开发实践》