levels of contents

设计模式python实现(02)--策略模式

设计模式python实现(02)--策略模式

面对算法时常变动

  • 内容:定义一系列的算法,把它们一个个封装起来,并且使得它们可以相互替换。本模式使得算法可独立于使用它的客户而变化。
  • 角色:
    • 抽象策略(Strategy)
    • 具体策略(ConcreteStrategy)
    • 上下文(Context)
"""
策略模式
author: panky
"""
import abc


class CashSuper(metaclass=abc.ABCMeta):
    """现金收费抽象类"""

    @abc.abstractmethod
    def accept_cash(self, money):
        pass


class CashNormal(CashSuper):
    """正常收费子类"""
    def accept_cash(self, money):
        return money


class CashRebate(CashSuper):
    """打折收费子类"""
    def __init__(self, discount=1.0):
        self.discount = discount

    def accept_cash(self, money):
        return money * self.discount


class CashReturn(CashSuper):
    """返利收费子类"""

    def __init__(self, money_condition=0, money_return=0):
        self.money_condition = money_condition
        self.money_return = money_return

    def accept_cash(self, money):
        if money >= self.money_condition:
            return money - (money / self.money_condition) * self.money_return
        return money


class Context(object):
    """具体策略类"""
    def __init__(self, cash_class_obj):
        self.cash_class_obj = cash_class_obj

    def get_result(self, money):
        return self.cash_class_obj.accept_cash(money)


if __name__ == "__main__":
    input_money = input("原价:")
    strategy = dict()
    strategy[1] = Context(CashNormal())
    strategy[2] = Context(CashRebate(0.8))
    strategy[3] = Context(CashReturn(100, 10))
    mode = input("选择折扣方式: 1)原价 2)8折 3)满100减10:")
    if int(mode) in strategy:
        c_super = strategy[int(mode)]
    else:
        print("不存在的折扣方式")
        c_super = strategy[1]
    print("pay: ", c_super.get_result(float(input_money)))

1264910-20171030111921261-14252556

使用一个策略类CashSuper定义需要的算法的公共接口,定义三个具体策略类:CashNormal,CashRebate,CashReturn,继承于CashSuper,定义一个上下文管理类,接收一个策略,并根据该策略得出结论,当需要更改策略时,只需要在实例的时候传入不同的策略就可以,免去了修改类的麻烦

posted @ 2020-08-21 08:36  panky  阅读(108)  评论(0编辑  收藏  举报