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

前端之家收集整理的这篇文章主要介绍了TypeScript实现设计模式——策略模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

——《大话设计模式》

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

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

Strategy接口

  1. interface Strategy {
  2. /**
  3. * 优惠活动
  4. * @param money 原价
  5. * @returns 现价
  6. */
  7. discount(money: number): number;
  8. }

具体的优惠策略

  1. // 满减优惠
  2. class FullAndReduceStrategy implements Strategy {
  3. // 满足条件的金额
  4. private conditionMoney: number;
  5. // 减少的金额
  6. private reduceMoney: number;
  7. constructor(money: number,returnMoney: number) {
  8. this.conditionMoney = money;
  9. this.reduceMoney = returnMoney;
  10. }
  11. public discount(money: number): number {
  12. let result: number;
  13. if (money >= this.conditionMoney) {
  14. result =
  15. money - Math.floor(money / this.conditionMoney) * this.reduceMoney;
  16. }
  17. return result;
  18. }
  19. }
  20. // 现金折扣
  21. class CashRebateStrategy implements Strategy {
  22. // 折扣值
  23. private moneyRabte: number;
  24. constructor(moneyRabte: number) {
  25. this.moneyRabte = moneyRabte;
  26. }
  27. discount(money: number): number {
  28. return money * this.moneyRabte;
  29. }
  30. }

Context类

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

  1. class Context {
  2. private strategy: Strategy;
  3. private money: number;
  4. constructor(money: number) {
  5. this.money = money;
  6. }
  7. // 设置优惠策略
  8. public setStrategy(strategy: Strategy): void {
  9. this.strategy = strategy;
  10. }
  11. // 执行策略
  12. public execute(): number {
  13. return this.strategy.discount(this.money);
  14. }
  15. }

测试

  1. const context: Context = new Context(100);
  2. context.setStrategy(new FullAndReduceStrategy(50,2));
  3. console.log(context.execute()); // 96
  4. context.setStrategy(new CashRebateStrategy(0.5));
  5. console.log(context.execute()); // 50

猜你在找的TypeScript相关文章