js设计模式-装饰器模式

装饰器模式

在不改变其原有的结构和功能为对象添加新功能,装饰比继承更加灵活。
就像你有一把狙击枪它需要消音的功能,我们就可以装上一个消音器。要一个四倍镜就可以
装上四倍镜,然后是握把,枪架等等。可以把消音器、四倍镜、握把、枪架…相当于装饰器概念。

// 狙击枪
  class SniperRifle {
    // 枪配置
    configuration() {
      return `狙击枪体`
    }
    // 枪的综合战力
    fightingCapacity() {
      return 2000
    }
  };

  // 消音器
  class Silencer {
    constructor(parent) {
      this.parent = parent;
    }
    // 枪配置
    configuration() {
      return `${this.parent.configuration()}+消音器`
    }
    // 枪的综合战力
    fightingCapacity() {
      return this.parent.fightingCapacity() + 100
    }
  };

  // 四倍镜
  class Telescope {
    constructor(parent) {
      this.parent = parent;
    }
    // 枪配置
    configuration() {
      return `${this.parent.configuration()}+四倍镜`
    }
    // 枪的综合战力
    fightingCapacity() {
      return this.parent.fightingCapacity() + 120
    }
  }
  // ...
  // 这可以扩展很多装饰器

  // 要一把狙击枪
  let sniperRifle1 = new SniperRifle();
  console.log(sniperRifle1.configuration())
  console.log(sniperRifle1.fightingCapacity())
  // 要一把有消音器的狙击枪
  let sniperRifle2 = new Silencer(new SniperRifle)
  console.log(sniperRifle2.configuration())
  console.log(sniperRifle2.fightingCapacity())
  // 要一把有消音器加四倍的狙击枪
  let sniperRifle3 = new Telescope(new Silencer(new SniperRifle))
  console.log(sniperRifle3.configuration())
  console.log(sniperRifle3.fightingCapacity())

这样可以在原有的功能上添加功能而不用修改原来的代码了,自由灵活性就很高。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值