定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换,本模式使得算法可独立于使用它的客户而发生变化
策略模式中的角色抽象策略(Strategy)具体策略(Concrete Strategy)上下文 策略模式的优点
定义了一系列可重用的算法和行为消除了一些条件语句可以提供相同行为的不同表现 策略模式的缺点
客户必须了解不同策略的特点 策略模式的实例
代码如下:
from abc import ABCmeta,abstractmethod
class Strategy(metaclass=ABCmeta):
@abstractmethod
def execute(self,data):
pass
class FastStrategy(Strategy):
def execute(self,data):
print(f"用较快的策略处理{data}")
class SlowStrategy(Strategy):
def execute(self,data):
print(f"用较慢的方式处理{data}")
class Context:
def __init__(self,strategy,data):
self.data=data
self.strategy=strategy
def set_strategy(self,strategy):
self.strategy=strategy
def do_strategy(self):
self.strategy.execute(self.data)
if __name__=="__main__":
data="[...]"
s1=FastStrategy()
s2 = SlowStrategy()
context=Context(s1,data)
context.do_strategy()
context = Context(s2, data)
context.do_strategy()
执行结果如下:
用较快的策略处理[...] 用较慢的方式处理[...]推荐阅读 设计模式(Python语言)----面向对象设计SOLID原则 设计模式(Python语言)----设计模式分类 设计模式(Python语言)----简单工厂模式 设计模式(Python语言)----工厂方法模式 设计模式(Python语言)----抽象工厂模式 设计模式(Python语言)----建造者模式 设计模式(Python语言)----单例模式 设计模式(Python语言)----适配器模式 设计模式(Python语言)----桥模式 设计模式(Python语言)----组合模式 设计模式(Python语言)----外观模式 设计模式(Python语言)----代理模式 设计模式(Python语言)----责任链模式 设计模式(Python语言)----观察者模式 设计模式(Python语言)----策略模式 设计模式(Python语言)----模板方法模式



