Strategy_Mode
文章目录
- 1. 策略模式
- 2. 代码实现:
1. 策略模式
策略模式主要用于一种行为模式,方便在算法的运行中不断的切换策略,有抽象类和具体类,是一种非常实用的设计方法。有利于程序的框架搭建和扩展
2. 代码实现:
- python 代码
from abc import ABC, abstractmethodclass Strategy(ABC):@abstractmethoddef execute(self, price):passclass DiscountStrategy(Strategy):def execute(self, price):return price * 0.9class NoDiscountStrategy(Strategy):def execute(self, price):return priceclass PromotionContext:def __init__(self, strategy: Strategy):self._strategy = strategydef set_strategy(self, strategy: Strategy):self._strategy = strategydef apply_discount(self, price):apply_discount = self._strategy.execute(price)print(f"{self._strategy.__class__.__name__} is for {apply_discount}")if __name__ == "__main__":promotion = PromotionContext(DiscountStrategy())promotion.apply_discount(100)promotion.set_strategy(NoDiscountStrategy())promotion.apply_discount(200)
- 运行结果:
DiscountStrategy is for 90.0
NoDiscountStrategy is for 200