Python设计模式中的行为型策略模式
作者:范桂飓 时间:2023-02-28 17:04:25
一、策略模式
策略模式中,首先定义了一系列不同的算法,并把它们一一封装起来,然后在策略类中,使这些算法可以相互替换。这意味着,让一个类的行为(算法)可以在类的实例化对象运行时进行更改。
优点:
定义了一系列可重用的算法和行为。
消除了一些条件语句。
可以提供相同行为的不同实现。
缺点:
Client
必须了解不同的策略行为细节。
二、应用场景
根据不同的客户属性,采用不同的折扣策略来计算订单中的商品价格:
有 1000 或以上积分的客户,每个订单享 5% 折扣。
同一订单中,单个商品的数量达到 20 个或以上,享 10% 折扣。
订单中的不同商品达到 10 个或以上,享 7% 折扣。
三、代码示例
实体角色:
上下文(Context):集成了算法的类。
抽象策略(Strategy):实现不同算法的组件的共同接口。
具体策略(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执行{data}")
# 具体策略2
class Strategy2(Strategy):
def execute(self, data):
print(f"使用策略2执行{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 = "测试数据"
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
标签:Python,设计模式,策略模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
循环神经网络TextRNN实现情感短文本分类任务
2021-12-14 04:24:26
![](https://img.aspxhome.com/file/2023/4/115504_0s.png)
html网页调用后端python代码的方法实例
2023-04-20 19:31:51
![](https://img.aspxhome.com/file/2023/0/121160_0s.png)
python笔记之mean()函数实现求取均值的功能代码
2022-01-12 07:06:47
asp如何让服务器延时执行更改后的数据?
2010-05-13 16:35:00
OverFlow – 一个秘密武器
2010-09-25 12:51:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/rss1-42s.png)
Python+Tkinter制作猜灯谜小游戏
2021-09-24 19:43:17
![](https://img.aspxhome.com/file/2023/7/66887_0s.gif)
golang跳转语句goto,break,continue的使用及区别说明
2024-04-23 09:39:56
MySQL实战窗口函数SQL分析班级学生考试成绩及生活消费
2024-01-15 08:56:14
![](https://img.aspxhome.com/file/2023/1/102381_0s.png)
python做翻译软件详解,小白也看得明白
2023-08-08 06:25:44
![](https://img.aspxhome.com/file/2023/6/91916_0s.png)
kali添加开机自启的方法
2023-06-06 04:15:06
![](https://img.aspxhome.com/file/2023/7/132317_0s.png)
ASP批量生成静态页面的写法(批量生成技巧iframe)
2011-02-24 11:01:00
Python os和os.path模块详情
2022-12-08 12:53:45
![](https://img.aspxhome.com/file/2023/2/89332_0s.png)
Python的包管理器pip更换软件源的方法详解
2023-02-03 05:25:22
python manage.py runserver流程解析
2022-03-11 13:12:10
Python线程之同步机制实际应用场景举例说明
2023-06-10 13:57:40
![](https://img.aspxhome.com/file/2023/0/76720_0s.png)
C# Oracle数据库操作类实例详解
2024-01-19 07:21:29
浅谈Python3中datetime不同时区转换介绍与踩坑
2021-05-16 15:29:46
Python使用PIL模块生成随机验证码
2022-03-05 21:54:11
jquery动态遍历Json对象的属性和值的方法
2024-06-09 00:53:36
如何把数据从SQL Server导出到Access或Excel中去?
2009-11-02 20:26:00