天天看點

javascript裝飾器模式javascript裝飾器模式

javascript裝飾器模式

function PlaneFactory() {
     this.decorate_list = [];
 }

 //建立對象接口
 PlaneFactory.create = function (type, x, y) {
     //判斷prototype上是否存在該類型的子類
     if (PlaneFactory.prototype[type] == undefined) {
         throw 'not this constructor!';
     }
     if (PlaneFactory.prototype[type].prototype.__proto__ != PlaneFactory.prototype) {
         // PlaneFactory.prototype[type].prototype.__proto__ = PlaneFactory.prototype;
         PlaneFactory.prototype[type].prototype = new PlaneFactory();
     }
     let arg = Array.from(arguments).slice(1);
     return new PlaneFactory.prototype[type](...arg);
 }

 PlaneFactory.prototype.die = function () {
     console.log('boom');
 }

 PlaneFactory.prototype.touch = function () {
     this.blood -= 50;
     console.log(this.blood);
     if (this.blood === 0) {
         this.die();
     }
 }

 PlaneFactory.prototype.decorators = {
     increaseOneBlood(obj) {
         obj.blood += 50;
     },
     increaseTwoBlood(obj) {
         obj.blood += 100;
     },
     decreaseOneBlood(obj) {
         obj.blood -= 50;
     },
     decreaseTwoBlood(obj) {
         obj.blood -= 100;
     }

 }
 
 PlaneFactory.prototype.decorate = function (decorate) {
     this.decorate_list.push(decorate);
 }
 
 PlaneFactory.prototype.delete = function (decorate) {
     let index = this.decorate_list.indexOf(decorate)
     this.decorate_list.splice(index,1);
 }

 PlaneFactory.prototype.empty = function () {
     this.decorate_list.length = 0;
 }

 PlaneFactory.prototype.update = function () {
     this.decorate_list.forEach(item => {
         this.decorators[item](this);
     })
 }

 PlaneFactory.prototype.SmallPlane = function (x, y) {
     this.x = x;
     this.y = y;
     this.width = 100;
     this.height = 125;
     this.blood = 100;
     this.name = 'SmallPlane';
 }

 PlaneFactory.prototype.BigPlane = function (x, y) {
     this.x = x;
     this.y = y;
     this.width = 150;
     this.height = 175;
     this.blood = 200;
     this.name = 'BigPlane';
 }

 PlaneFactory.prototype.AttachPlane = function (x, y) {
     this.x = x;
     this.y = y;
     this.width = 100;
     this.height = 150;
     this.blood = 150;
     this.name = 'AttachPlane';
     this.attach = function () {
         console.log('biu~biu~biu~');
     }
 }

 const ap = new PlaneFactory.create('AttachPlane', 20, 30);
 ap.decorate('increaseOneBlood');
 ap.decorate('increaseTwoBlood');
 ap.delete('increaseTwoBlood');
 // ap.empty();
 ap.update();
 // ap.decorate('increaseOneBlood');
 const bp = new PlaneFactory.create('BigPlane', 30, 40);
 const sp = new PlaneFactory.create('SmallPlane', 10, 15);
           

繼續閱讀