python---策略模式


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 語句。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM