一、装饰者
装饰者模式 : 装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。
1、下面演示仿java版本的装饰者模式。
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();
2、采用aop的方式进行扩展方法功能。
// 原方法
var sum = function (a, b, c) {
var arr = Array.prototype.slice.call(arguments);
var s = 0;
for (let i = 0; i < arr.length; i++) {
s += arr[i];
}
return s;
}
// 对所有方法原型上增