python设计模式之策略模式

  每次看到项目中存在大量的if else代码时,都会心生一丝不安全感。 特别是产品给的需求需要添加或者更改一种if条件时,生怕会因为自己的疏忽而使代码天崩地裂,哈哈,本文的目的就是来解决这种不安全感的,23种设计模式的策略模式。

  GOF对策略模式的解释是: 定义一系列算法, 把它们一个个封装起来,并且使它们可相互替换(变化)。该模式使得算法可独立于使用它的客户程序(稳定)而变化(扩展, 子类化)。

 

  策略模式结构图如下:

python设计模式之策略模式

 

  生活中商场搞活动给消费者派送了一批优惠券,优惠券分三种, 一种是满减券满100减10元, 一种是打折券满200打8折, 一种折扣券是满300打7.5折然后送鸡蛋一打(价值15),如果我们是商场后台程序员,我们要计算每个客户最后实际支付了多少钱,那这个程序你会怎样去设计?

 

01、 没有使用设计模式的版本

class Order: def __init__(self, money, coupon): self.money = money self.coupon = coupon def total_money(self): if self.coupon == 1 and self.money >= 100: return self.money - 10 elif self.coupon == 2 and self.money >= 200: return self.money * 0.8 elif self.coupon == 3 and self.money >= 300: return self.money * 0.75 -15 return self.money if __name__ == '__main__': order1 = Order(102, 1) order2 = Order(250, 2) order3 = Order(372, 3) order4 = Order(190, 2) o1 = order1.total_money() o2 = order2.total_money() o3 = order3.total_money() o4 = order4.total_money() print(o1, o2, o3, o4)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpspdx.html