Python 设计模式--策略模式
发布日期:2022-03-30 18:18:19 浏览次数:50 分类:博客文章

本文共 2603 字,大约阅读时间需要 8 分钟。

  策略模式(Strategy Pattern)

  策略模式是一种与行为相关的设计模式,允许你在运行时根据指定的上下文确定程序的动作。可以在两个类中封装不同的算法,并且在程序运行时确定到底执行哪中策略。

  特点:定义算法家族,分别封装起来,让它们之间可以互相替换。此模式让算法的变化不会影响到使用算法的客户。

  《大话设计模式》中实例:超市收银软件。

  代码:

#!/usr/bin/env python#-*- coding: utf-8 -*-class CashSuper():    def acceptCash(self):        passclass CashNormal(CashSuper):    def accept(slef,money):        return moneyclass CashRebate(CashSuper):    moneyRebate = 0.0    def __init__(self,rebate):        self.moneyRebate = rebate    def acceptCash(self,money):        return money*self.moneyRebateclass 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 resultclass 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):        passclass 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()

 

转载地址:https://www.cnblogs.com/cloudPython/p/4913537.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spark2.4.0源码——TaskScheduler
下一篇:Ubantu 16.04中文输入问题解疑

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月06日 17时25分45秒