python---策略模式

来源:https://www.cnblogs.com/failymao/archive/2020/03/10/12455840.html
-Advertisement-
Play Games

[TOC] python–策略模式 前言 策略模式作為一種軟體設計模式,指對象有某個行為,但是在不同的場景中,該行為有不同的實現演算法。 策略模式: 定義了一族演算法(業務規則); 封裝了每個演算法; 這族的演算法可互換代替(interchangeable) 不會影響到使用演算法的客戶. 結構圖 一. 應用 ...


目錄

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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 【一統江湖的大前端(8)】matter.js 經典物理 示例代碼托管在: "http://www.github.com/dashnowords/blogs" 博客園地址: "《大史住在大前端》原創博文目錄" 華為雲社區地址: "【你要的前端打怪升級指南】" [TOC] 在前端開發領域,物理引擎是一個 ...
  • 安裝electron 上次安裝node sass即使用了淘寶鏡像源也還是安裝不上( "解決方法" ),這次又遇到了一個用鏡像源也安裝不上的 就是electron,安裝在某一點卡死,一直不動 原因是這樣的:因為 npm 需要連接 github 下載 electron 安裝包導致,安裝包有 60M 左右 ...
  • 需求:最近項目開發中使用elementUI的表格組件,表格頭部設置label的時候只能是字元串,想在表格頭部添加自定義的html標簽。 解決方法:使用render-header 在column上綁定render-header屬性 <el-table-column :label="地址" :rende ...
  • 1、文本:使用 {{...}}(雙大括弧)的文本插值 <div id="app"> <p>{{ message }}</p> </div> 2、html 使用v-html指令輸出html的值 3、屬性:屬性的值使用v-bind 以下實例判斷 class1 的值,如果為 true 使用 class1 ...
  • 表格: thead 表頭 tbody 表體 tfoot 表尾 th 列標題,預設居中加粗的td caption 表格表體,預設左右居中 colgroup span="num" 列分組 表格屬性: border-spacing:單元格間距,必須給table添加 border-collapse:coll ...
  • 我們要為路由提供請求的 URL 和其他需要的 GET 及 POST 參數,隨後路由需要根據這些數據來執行相應的代碼。 我們需要的所有數據都會包含在 request 對象中,該對象作為 onRequest() 回調函數的第一個參數傳遞。 但是為瞭解析這些數據,我們需要額外的 Node.JS 模塊,它們 ...
  • 一個函數可以作為另一個函數的參數 function fn1(fn,arg){ fn(arg); } function name(n){ console.log("i am "+n); } fn1(name,"cyy"); 使用匿名函數 function fn1(fn,arg){ fn(arg); } ...
  • Node.js中的Stream 有四種流類型: Readable - 可讀操作。 Writable - 可寫操作。 Duplex - 可讀可寫操作. Transform - 操作被寫入數據,然後讀出結果。 所有的 Stream 對象都是 EventEmitter 的實例。常用的事件有: data - ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...