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

  • Post author:
  • Post category:其他




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

策略模式(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) 



版权声明:本文为weixin_43783363原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。