網(wǎng)站首頁 編程語言 正文
一、策略模式
策略模式中,首先定義了一系列不同的算法,并把它們一一封裝起來,然后在策略類中,使這些算法可以相互替換。這意味著,讓一個類的行為(算法)可以在類的實例化對象運行時進(jìn)行更改。
優(yōu)點:
- 定義了一系列可重用的算法和行為。
- 消除了一些條件語句。
- 可以提供相同行為的不同實現(xiàn)。
缺點:
-
Client
必須了解不同的策略行為細(xì)節(jié)。
二、應(yīng)用場景
根據(jù)不同的客戶屬性,采用不同的折扣策略來計算訂單中的商品價格:
- 有 1000 或以上積分的客戶,每個訂單享 5% 折扣。
- 同一訂單中,單個商品的數(shù)量達(dá)到 20 個或以上,享 10% 折扣。
- 訂單中的不同商品達(dá)到 10 個或以上,享 7% 折扣。
三、代碼示例
實體角色:
- 上下文(Context):集成了算法的類。
- 抽象策略(Strategy):實現(xiàn)不同算法的組件的共同接口。
- 具體策略(Concrete Strategy):抽象策略的具體子類。
import abc # 抽象策略 class Strategy(metaclass=abc.ABCMeta): ? ? @abc.abstractmethod ? ? def execute(self, data): ? ? ? ? pass # 具體策略 1 class Strategy1(Strategy): ? ? def execute(self, data): ? ? ? ? print(f"使用策略1執(zhí)行{data}") # 具體策略2? class Strategy2(Strategy): ? ? def execute(self, data): ? ? ? ? print(f"使用策略2執(zhí)行{data}") # 上下文 class Context: ? ? def __init__(self, data): ? ? ? ? self.strategy = None ? ? ? ? self.data = data ? ? def set_strategy(self, strategy): ? ? ? ? self.strategy = strategy ? ? def do_strategy(self): ? ? ? ? if self.strategy: ? ? ? ? ? ? self.strategy.execute(self.data) ? ? ? ? else: ? ? ? ? ? ? print("請先配置策略!") if __name__ == "__main__": ? ? data = "測試數(shù)據(jù)" ? ? s1 = Strategy1() ? ? s2 = Strategy2() ? ? context = Context(data) ? ? context.set_strategy(s1) ? ? context.do_strategy() ? ? context.set_strategy(s2) ? ? context.do_strategy()
原文鏈接:https://is-cloud.blog.csdn.net/article/details/122929628
相關(guān)推薦
- 2022-07-13 C# System.Web.HttpContext.Current.Server.MapPath 報
- 2022-05-13 C/C++: __builtin_popcount 函數(shù)及其一些 __builtin函數(shù)
- 2022-11-17 python數(shù)學(xué)模塊(math/decimal模塊)_python
- 2022-04-16 C++中allocator類使用示例_C 語言
- 2022-07-08 C#使用WebClient實現(xiàn)上傳下載_C#教程
- 2022-11-28 基于Python實現(xiàn)DIT-FFT算法_python
- 2024-04-08 啟動spring-boot出現(xiàn)Error creating bean with name ‘conf
- 2023-03-17 git?push時卡住的解決方法(長時間不報錯也不自動退出)_相關(guān)技巧
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支