策略模式(Strategy Pattern)
策略模式是一种与行为相关的设计模式,允许你在运行时根据指定的上下文确定程序的动作。可以在两个类中封装不同的算法,并且在程序运行时确定到底执行哪中策略。
特点:定义算法家族,分别封装起来,让它们之间可以互相替换。此模式让算法的变化不会影响到使用算法的客户。
《大话设计模式》中实例:超市收银软件。
代码:
#!/usr/bin/env python #-*- coding: utf-8 -*- class CashSuper(): def acceptCash(self): pass class CashNormal(CashSuper): def accept(slef,money): return money class CashRebate(CashSuper): moneyRebate = 0.0 def __init__(self,rebate): self.moneyRebate = rebate def acceptCash(self,money): return money*self.moneyRebate class CashReturn(CashSuper): m_moneyCondition = 0.0 m_moneyReturn = 0.0 def __init__(self,moneyCondition,moneyReturn): self.m_moneyCondition = moneyCondition self.m_moneyReturn = moneyReturn def acceptCash(self,money): if(money>self.m_moneyCondition): result = money - (money/self.m_moneyCondition)*self.m_moneyReturn else: result = money return result class CashContext(): def __init__(self,choice): self.s_cash = choice def getCash(self,money): return self.s_cash.acceptCash(money) if __name__ == "__main__": money = input("Enter the money:") strategy = {} strategy[1] = CashContext(CashNormal) strategy[2] = CashContext(CashRebate) strategy[3] = CashContext(CashReturn(300,100)) cash_type = input("Type: [1]for normal; [2]for 80% discount; [3]for 300 - 100.") if(cash_type in strategy.keys()): cash_strategy = strategy[cash_type] else: print(u"未定义的收费模式!使用正常收费!") cash_strategy = strategy[1] real_money = cash_strategy.getCash(money) print(u"实际付款:" + str(real_money)) #print("实际付款:%d"%real_money)
步骤:
1、定义Strategy类,定义所有支持的算法的公共接口
2、定义ConcreteStrategy类,封装具体的算法或方法,继承于Strategy类
3、定义Context类,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。
#!/usr/bin/env python #-*- coding: utf-8 -*- class Strategy(): def AlgorithmInterface(self): pass class ConcrateStrategyA(Strategy): def AlgorithmInterface(self): print("算法A实现!") class ConcrateStrategyB(Strategy): def AlgorithmInterface(self): print("算法B实现!") class ConcrateStrategyC(Strategy): def AlgorithmInterface(self): print("算法C实现!") class Context(): def __init__(self,choice): self.contextsuper = choice def ContextInterface(self): self.contextsuper.AlgorithmInterface() if __name__ == "__main__": context = Context(ConcrateStrategyA()) context.ContextInterface() context = Context(ConcrateStrategyB()) context.ContextInterface() context = Context(ConcrateStrategyC()) context.ContextInterface()