策略模式

意图:定义一系列的算法,将他们分别封装起来,并且是他们相互之间可以替换
主要解决:if...else问题

结构:客户端,策略接口,具体策略
主要技术:使用装饰器@property将策略接口类中的方法变为属性,以及使用装饰器@方法名.setter来动态的修改属性,已达到在客户端动态改变策略的目的

案例
商场促销活动,同时推出多种促销方案供给顾客选择。一种方案是直接打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发现了有技术含量的博客,小伙伴们求同去《Python设计模式之策略模式(15)》, 一起来围观吧 https://blog.csdn.net/biheyu/article/details/101690474?utm_source=app&app_version=5.0.1&code=app_1562916241&uLinkId=usr1mkqgl919blen

你可能感兴趣的:(策略模式)