意圖:定義一系列的算法,將他們分別封裝起來粘都,并且是他們相互之間可以替換
主要解決:if...else問題
結(jié)構(gòu):客戶端廓推,策略接口,具體策略
主要技術(shù):使用裝飾器@property將策略接口類中的方法變?yōu)閷傩贼嫠恚约笆褂醚b飾器@方法名.setter來動態(tài)的修改屬性受啥,已達到在客戶端動態(tài)改變策略的目的
案例
商場促銷活動,同時推出多種促銷方案供給顧客選擇。一種方案是直接打9折滚局,另一種方案是滿1000元打八折再送50元抵扣券
from abc import ABC, abstractmethod
class Strategy(ABC):
@abstractmethod
def discount(self, order):
pass
class StrategyA(Strategy):
def discount(self, order):
return order._price * 0.1
class StrategyB(Strategy):
def discount(self, order):
return order._price * 0.2 + 50
class OrderContext(object):
def __init__(self, price, discount_strategy=None):
self._price = price
self._strategy = discount_strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy):
self._strategy = strategy
def price_with_discount(self):
if self._strategy:
discount = self._strategy.discount(self)
else:
discount = 0
pay = self._price - discount
print(f'折扣策略{type(self._strategy).__name__},原價{self._price}, 折扣價: {pay}')
return pay
def main():
order = OrderContext(1000)
order.price_with_discount()
st = StrategyA()
order.strategy = st
order.price_with_discount()
st2 = StrategyB()
order.strategy = st2
order.price_with_discount()
if __name__ == "__main__":
main()
來源:我用#CSDN#這個app發(fā)現(xiàn)了有技術(shù)含量的博客,小伙伴們求同去《Python設(shè)計模式之策略模式(15)》, 一起來圍觀吧 https://blog.csdn.net/biheyu/article/details/101690474?utm_source=app&app_version=5.0.1&code=app_1562916241&uLinkId=usr1mkqgl919blen