一个简单的函数,带你认清楚装饰器模式的本质

194 阅读1分钟

义如其名,就是在原有的特征至上,装饰一些新的特征。也就是入参是一个function,执行结果是返回一个新的function,如decorator=(fn)=>{return ()=>{...}}

妹子爱玩的装扮游戏,就能很好的介绍装饰器模式。假设一个妹子,只穿了内衣和内裤,其他的衣服可以自由装扮,只要衣物不属于同一个属性,就可以持续添加,如果属于同一个属性,则被覆盖。

在实际开发中,这里的属性可以包括属性或者方法。

/**
 * decorator装饰器
 */

class Girl {
  constructor(name) {
    this.name = name;
  }
  say() {
    let s = `我的名字是${this.name},我`;
    if (this.hat) {
      s += `戴了${this.hat},`;
    } else {
      s += "没戴帽子,";
    }

    if (this.cloth) {
      s += `穿了${this.cloth},`;
    } else {
      s += "没穿衣服,";
    }

    if (this.trousers) {
      s += `穿的裤子是${this.trousers},`;
    } else {
      s += "没穿裤子,";
    }
    console.log(s);
  }
}
Girl.prototype.hat = undefined;
Girl.prototype.cloth = undefined;
Girl.prototype.trousers = undefined;

//装饰器
function Hat(girlClass, hatName) {
  girlClass.prototype.hat = hatName;
  return girlClass;
}

//装饰器衣服
function Cloth(girlClass, hatName) {
  girlClass.prototype.cloth = hatName;
  return girlClass;
}

//装饰器衣服
function Trousers(girlClass, hatName) {
  girlClass.prototype.trousers = hatName;
  return girlClass;
}

const HatedGigleClass = Hat(Girl, "鸭舌帽");
const hg = new HatedGigleClass("马丽");
hg.say();
setTimeout(() => {
  const ClothedGirlClass = Cloth(HatedGigleClass, "风衣");
  const cg = new ClothedGirlClass("马丽");
  cg.say();
  setTimeout(() => {
    const TrousereddGirlClass = Cloth(ClothedGirlClass, "牛仔裤");
    const tg = new TrousereddGirlClass("马丽");
    tg.say();
  });
});

【使用场景】

根据需要增加属性,比如有的类需要设置redux的状态管理功能,可以根据需要添加对应的属性和方法。

【code执行参考】 codesandbox.io/s/ge-zhong-…