python---策略模式

目录
  • python–策略模式

    • 前言
    • 一. 应用
    • 二. 避免过多使用if…else
    • 三. 使用策略,工厂模式.

python–策略模式

前言

策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。

策略模式:

  • 定义了一族算法(业务规则);
  • 封装了每个算法;
  • 这族的算法可互换代替(interchangeable)
  • 不会影响到使用算法的客户.

结构图

一. 应用

下面是一个商场的活动实现

#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~

# 现金收费抽象类
class CashSuper(object):

    def accept_cash(self, money):
        pass

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

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

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

class CashReturn(CashSuper):
    """策略3 返利收费子类"""
    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_super):
        self.cash_super = cash_super

    def GetResult(self, money):
        return self.cash_super.accept_cash(money)

if __name__ == '__main__':
    money = input("原价: ")
    strategy = {}
    strategy[1] = Context(CashNormal())
    strategy[2] = Context(CashRebate(0.8))
    strategy[3] = Context(CashReturn(100, 10))
    mode = int(input("选择折扣方式: 1) 原价 2) 8折 3) 满100减10: "))
    if mode in strategy:
        cash_super = strategy[mode]
    else:
        print("不存在的折扣方式")
        cash_super = strategy[1]
    print("需要支付: ", cash_super.GetResult(money))

类的设计图如下

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

二. 避免过多使用if…else

对于业务开发来说,业务逻辑的复杂是必然的,随着业务发展,需求只会越来越复杂,为了考虑到各种各样的情况,代码中不可避免的会出现很多if-else。

一旦代码中if-else过多,就会大大的影响其可读性和可维护性。

首先可读性,不言而喻,过多的if-else代码和嵌套,会使阅读代码的人很难理解到底是什么意思。尤其是那些没有注释的代码。

其次是可维护性,因为if-else特别多,想要新加一个分支的时候,就会很难添加,极其容易影响到其他的分支。

下面来介绍如何使用策略模式 消除if …else

示例: 将如下函数改写成策略模式

# pay_money.py
#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~

def get_result(type, money):
    """商场促销"""
    result = money
    if money > 10000:
        if type == "UserType.SILVER_VIP":
            print("白银会员 优惠50元")
            result = money - 50
        elif type == "UserType.GOLD_VIP":
            print("黄金会员 8折")
            result = money * 0.8

        elif type == "UserType.PLATINUM_VIP":
            print("白金会员 优惠50元,再打7折")
            result = money * 0.7 - 50
        else:
            print("普通会员 不打折")
            result = money

    return result

策略模式如下

class CashSuper(object):
    """收款抽象类"""

    def pay_money(self,money):
        pass

class SilverUser(CashSuper):
    """策略1:白银会员收费模式"""

    def __init__(self, discount_money=50):
        self.discount_money = discount_money

    def pay_money(self,money):
        return money - self.discount_money

class GoldUser(CashSuper):
    """策略2: 黄金会员收费模式"""
    def __init__(self,discount=0.8):
        self.discount = discount

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

class PlatinumUser(CashSuper):
    """策略3: 白金会员收费模式"""

    def __init__(self,discount_money=50,discount=0.7):
        self.discount_money = discount_money
        self.discount = discount

    def pay_money(self,money):
        if money >= self.discount_money:
            return money* self.discount - self.discount_money
        return money

class NormalUser(CashSuper):
    """策略4: 正常会员不打折"""

    def pay_money(self,money):
        return money

class Context(object):
    """具体实现的策略类"""

    def __init__(self,cash_super):
        """初始化:将策略类传递进去作为属性"""
        self.cash_super = cash_super

    def get_result(self,money):
        return self.cash_super.pay_money(money)

def main(money, user_type):
    """程序入口"""
if money  < 1000:
return money
    if user_type == "UserType.SILVER_VIP":
        strategy = Context(SilverUser())
    elif user_type == "UserType.GOLD_VIP":
        strategy = Context(GoldUser())
    elif user_type == "UserType.PLATINUM_VIP":
        strategy = Context(PlatinumUser())
    else:
        strategy = Context(NormalUser())

    return strategy.get_result(money)

三. 使用策略,工厂模式.

代码如下

#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~

"""
使用策略模式 + 工厂模式
"""

class StrategyFactory(object):
    """工厂类"""
    strategy = {}

    @classmethod
    def get_strategy_by_type(cls, type):
        """类方法:通过type获取具体的策略类"""
        return cls.strategy.get(type)

    @classmethod
    def register(cls, strategy_type, strategy):
        """类方法:注册策略类型"""
        if strategy_type == "":
            raise Exception("strategyType can't be null")
        cls.strategy[strategy_type] = strategy

class CashSuper(object):
    """收款抽象类"""

    def pay_money(self, money):
        pass

    def get_type(self):
        pass

class SilverUser(CashSuper):
    """策略1:白银会员收费模式"""

    def __init__(self, discount_money=50):
        self.discount_money = discount_money

    def pay_money(self, money):
        return money - self.discount_money

    def get_type(self):
        return "UserType.SILVER_VIP"

    def collect_context(self):
        StrategyFactory.register(self.get_type(), SilverUser)

class GoldUser(CashSuper):
    """策略2: 黄金会员收费模式"""

    def __init__(self, discount=0.8):
        self.discount = discount

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

    def get_type(self):
        return "UserType.GOLD_VIP"

    def collect_context(self):
        StrategyFactory.register(self.get_type(), GoldUser)

class PlatinumUser(CashSuper):
    """策略3: 白金会员收费模式"""

    def __init__(self, discount_money=50, discount=0.7):
        self.discount_money = discount_money
        self.discount = discount

    def pay_money(self, money):
        if money >= self.discount_money:
            return money * self.discount - self.discount_money
        return money

    def get_type(self):
        return "UserType.PLATINUM_VIP"

    def collect_context(self):
        StrategyFactory.register(self.get_type(), PlatinumUser)

class NormalUser(CashSuper):
    """策略4: 正常会员不打折"""

    def pay_money(self, money):
        return money

    def get_type(self):
        return "UserType.Normal"

    def collect_context(self):
        StrategyFactory.register(self.get_type(), NormalUser)

def InitialStrategys():
    """初始化方法:收集策略函数"""
    NormalUser().collect_context()
    PlatinumUser().collect_context()
    GoldUser().collect_context()
    SilverUser().collect_context()

def main(money, type):
    """入口函数"""
    InitialStrategys()
    strategy = StrategyFactory.get_strategy_by_type(type)
    if not strategy:
        raise Exception("please input right type!")
    return strategy().pay_money(money)

if __name__ == "__main__":
    money = int(input("show money:"))
    type = input("Pls input user Type:")
    result = main(money, type)
    print("should pay money:", result)

通过一个工厂类StrategyFactory,在我们在调用register类方法时将策略收集到策略中,根据传入 type,即可获取到对应 Strategy

消灭了大量的 if-else 语句。

(0)

相关推荐

  • 设计模式——把类作为参数的抽象工厂模式

    今天给大家介绍一个非常简单的设计模式,一学就会,非常好用. 这个模式叫做抽象工厂模式,大家可能对工厂模式比较熟悉,在工厂模式当中封装了实例的创建逻辑.主要的用途一般是将一些复杂的类的创建过程整合在一起 ...

  • 2.7万 Star!最全面的 Python 设计模式集合

    [导语]:设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易地被他人理解.保证代码可靠性.python-patterns 则是使用 ...

  • 聊聊 Python 面试最常被问到的几种设计模式(下)

    聊聊 Python 面试最常被问到的几种设计模式(下)

  • Python中的单例模式有几种实现方式?

    公众号新增加了一个栏目,就是每天给大家解答一道Python常见的面试题,反正每天不贪多,一天一题,正好合适,只希望这个面试栏目,给那些正在准备面试的同学,提供一点点帮助! 小猿会从最基础的面试题开始, ...

  • PyPattyrn-一个简单而有效的python库,用于实现常见的设计模式

    PyPattyrn是一个python软件包,旨在使您更轻松,更快地将设计模式实现到您自己的项目中. 设计模式本质上不能直接转换为代码,因为它们只是对如何解决特定问题的描述.但是,许多常见的设计模式都具 ...

  • Python单例模式(Singleton)的N种实现

    很多初学者喜欢用全局变量,因为这比函数的参数传来传去更容易让人理解.确实在很多场景下用全局变量很方便.不过如果代码规模增大,并且有多个文件的时候,全局变量就会变得比较混乱.你可能不知道在哪个文件中定义 ...

  • Python中的多态如何理解?

    Python中多态的作用 让具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同内容(功能)的函数. Python中多态的特点 1.只关心对象的实例方法是否同名,不关心对象所属的类型 ...

  • 深度强化学习DDPG在量化投资的应用

    主动基金被动管,被动基金主动管. 所以,我们的模型主要应用于场内ETF,ETF可以随时交易且手续费相对较低.而且ETF是支持T+0的. 继续强化学习. 今天探讨一下这DDPG:深度确定性策略梯度(De ...

  • TypeScript实现设计模式——策略模式

    策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的客户. --<大话设计模式> 策略模式主要用来解决当有多种相似算 ...

  • vscode 的python 交互模式

    前提安装了vscode的插件, 本地安装了python程序,并且pip 安装ipykernel black magic 一切开始于#%% shift-enter 就可以方便的输出运行结果 输入os.l ...

  • 点外卖,让我想起了 策略模式【原创】

    回复"000"获取大量电子书 本篇文章是设计模式系列的第三篇: 模板模式 单例模式 今天给大家分享的是策略模式,具体内容大纲如下: 生活案例 在这互联网时代,尤其是在城市中,有一帮 ...

  • PHP设计模式之策略模式

    PHP设计模式之策略模式 策略模式,又称为政策模式,属于行为型的设计模式. Gof类图及解释 GoF定义:定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换.本模式使得算法可独立于使用它的 ...

  • [PHP小课堂]PHP设计模式之策略模式

    [PHP小课堂]PHP设计模式之策略模式 关注公众号:[硬核项目经理]获取最新文章 添加微信/QQ好友:[DarkMatterZyCoder/149844827]免费得PHP.项目管理学习资料

  • 设计模式之策略模式

    策略模式 Strategy Intro 策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的 Context. 策略模式是一种定 ...

  • 设计模式——策略模式

    什么是策略模式?策略模式属于对象的行为模式.其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换.策略模式使得算法可以在不影响到客户端的情况下发生变化.举个例子? ...

  • python 无头模式

    1.1.1 Python来源(了解) Python翻译成汉语是蟒蛇的意思,并且Python的logo也是两条缠绕在一起的蟒蛇的样子,然而Python语言和蟒蛇实际上并没有一毛钱关系. Python语言 ...

  • PHP设计模式—策略模式

    定义: 策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户. 结构: Strategy(策略类):定义所有支持的算法的公 ...

  • 设计模式(22) 策略模式

    在策略模式中,一个类的行为或算法可以在运行时动态更改. GOF对策略模式的描述为: Define a family of algorithms, encapsulate each one, and m ...

  • 设计模式-策略模式

    示例 策略模式是我们工作中比较常用的一个设计模式,但是初次理解起来可能会有点困难,因此我们还是先看一个例子,假设现在需要开发一个画图工具,画图工具中有钢笔,笔刷和油漆桶,其中,钢笔可以用于描边,但不能 ...