当前位置: 移动技术网 > IT编程>软件设计>设计模式 > TypeScript实现设计模式——策略模式

TypeScript实现设计模式——策略模式

2020年03月22日  | 移动技术网IT编程  | 我要评论

策略模式(strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的客户。

——《大话设计模式》

策略模式主要用来解决当有多种相似算法的时,使用if...else产生的难以维护的问题。它主要由三部分组成:strategy接口、具体的strategy类以及用来改变和执行策略的context类。

接下来将以一个超市选择优惠活动的例子实现策略模式。

strategy接口

interface strategy {
  /**
   * 优惠活动
   * @param money 原价
   * @returns 现价
   */
  discount(money: number): number;
}

具体的优惠策略

// 满减优惠
class fullandreducestrategy implements strategy {
  // 满足条件的金额
  private conditionmoney: number;
  // 减少的金额
  private reducemoney: number;

  constructor(money: number, returnmoney: number) {
    this.conditionmoney = money;
    this.reducemoney = returnmoney;
  }

  public discount(money: number): number {
    let result: number;

    if (money >= this.conditionmoney) {
      result =
        money - math.floor(money / this.conditionmoney) * this.reducemoney;
    }

    return result;
  }
}

// 现金折扣
class cashrebatestrategy implements strategy {
  // 折扣值
  private moneyrabte: number;

  constructor(moneyrabte: number) {
    this.moneyrabte = moneyrabte;
  }

  discount(money: number): number {
    return money * this.moneyrabte;
  }
}

context类

setstrategy方法用来控制要使用的策略,execute方法用来执行策略。

class context {
  private strategy: strategy;
  private money: number;

  constructor(money: number) {
    this.money = money;
  }

  // 设置优惠策略
  public setstrategy(strategy: strategy): void {
    this.strategy = strategy;
  }

  // 执行策略
  public execute(): number {
    return this.strategy.discount(this.money);
  }
}

测试

const context: context = new context(100);

context.setstrategy(new fullandreducestrategy(50, 2));
console.log(context.execute()); // 96

context.setstrategy(new cashrebatestrategy(0.5));
console.log(context.execute()); // 50

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网