定义
在不改变元对象的基础上,通过对其进行包装拓展(添加属性方法),装饰者模式能够在不改变对象自身的基础上,在程序运行期间动态对象动态的添加职责。与继承相比,装饰者是一种更轻便灵活的做法。可以当脚本运行时,在子类中增加行为会影响原有类所有的实例,而装饰者却不然。取而代之的是它能给不同对象各自添加新行为和属性。
接着工厂方法模式说,创建好了飞机工厂,然后去装修它
//工厂方法模式
function PlaneFactor() {
this.decorate_list = []
}
//集合所有装饰方法
PlaneFactor.prototype.decorators = {
eatOneLife(obj){
obj.blod += 100
},
eatTwoLife(obj){
obj.blod += 200
},
eatShrinkLife(obj){
obj.blod -= 50
}
}
//搜集对某对象的装饰描述
PlaneFactor.prototype.decorate= function(decorator){
this.decorate_list.push(decorator)
}
//让装饰方法作用在改对象身上
PlaneFactor.prototype.update = function(){
for(var i = 0; i < this.decorate_list.length; i++){
this.decorators[this.decorate_list[i]] && this.decorators[this.decorate_list[i]](this)
}
}
//清除
PlaneFactor.prototype.empty = function(){
this.decorate_list = []
}
//删除
PlaneFactor.prototype.remove = function (type) {
this.decorate_list = this.decorate_list.filter((ele)=>{
return !(ele == type)
})
}
//子类工厂都可以使用的公共方法
PlaneFactor.prototype.touch = function () {
this.blod -= 50;
if (this.blod == 0) {
console.log('die')
}
}
PlaneFactor.prototype.die = function(){
console.log('bong')
}
//创建对象的接口
PlaneFactor.create = function (type) {
//是否存在改类型的子类工厂
if (PlaneFactor.prototype[type] == undefined) {
throw 'no this constructor'
}
//继承
if (PlaneFactor.prototype[type].prototype.__proto__ != PlaneFactor.prototype) {
PlaneFactor.prototype[type].prototype = new PlaneFactor()
}
var arg = [].slice.call(arguments,1)
var newPlane = new PlaneFactor.prototype[type](...arg)
return newPlane;
}
//真正定义子类工厂
PlaneFactor.prototype.SmallPlane = function (x, y) {
this.x = x;
this.y = y;
this.height = 100
this.width = 100
this.name = 'SmallPlane'
this.blod = 100
}
PlaneFactor.prototype.BigPlane = function (x,y) {
this.x = x;
this.y = y;
this.height = 200
this.width = 200
this.blod = 200
this.name = 'BigPlane'
}
PlaneFactor.prototype.AtackPlane = function (x,y) {
this.x = x;
this.y = y;
this.height = 125;
this.width = 100
this.blod = 100
this.name = 'AtackPlane'
this.attack = function () {
console.log('biu')
}
}
var a= PlaneFactor.create('AtackPlane',10,20)
var b= PlaneFactor.create('BigPlane',20,20)
var c= PlaneFactor.create('SmallPlane',40,20)
// 装饰者模式
a.decorate('eatOneLife')
a.decorate('eatTwoLife')
b.decorate('eatTwoLife')