推荐答案
// www.javascriptcn.com code example
from abc import ABC, abstractmethod
# 定义策略接口
class Strategy(ABC):
@abstractmethod
def execute(self, data):
pass
# 具体策略A
class StrategyA(Strategy):
def execute(self, data):
return f"Strategy A executed with {data}"
# 具体策略B
class StrategyB(Strategy):
def execute(self, data):
return f"Strategy B executed with {data}"
# 上下文类
class Context:
def __init__(self, strategy: Strategy):
self._strategy = strategy
def set_strategy(self, strategy: Strategy):
self._strategy = strategy
def execute_strategy(self, data):
return self._strategy.execute(data)
# 使用策略模式
context = Context(StrategyA())
print(context.execute_strategy("Data 1")) # 输出: Strategy A executed with Data 1
context.set_strategy(StrategyB())
print(context.execute_strategy("Data 2")) # 输出: Strategy B executed with Data 2本题详细解读
策略模式的定义
策略模式(Strategy Pattern)是一种行为设计模式,它允许你定义一系列算法,并将每个算法封装起来,使它们可以互换。策略模式使得算法可以独立于使用它的客户端而变化。
策略模式的结构
- 策略接口(Strategy):定义所有支持的算法的公共接口。通常是一个抽象类或接口。
- 具体策略(Concrete Strategy):实现策略接口的具体算法。
- 上下文(Context):持有一个策略对象的引用,并通过策略接口与具体策略进行交互。
策略模式的优点
- 开闭原则:可以在不修改现有代码的情况下引入新的策略。
- 避免条件语句:通过使用策略对象,可以避免使用大量的条件语句来选择不同的算法。
- 提高代码复用性:策略模式将算法的实现与使用分离,使得算法可以在不同的上下文中复用。
策略模式的适用场景
- 当一个系统需要在运行时动态选择算法时。
- 当一个类有多种行为,并且这些行为在类的操作中以多个条件语句的形式出现时。
- 当希望将算法的实现与使用算法的类分离时。
代码示例解析
Strategy是一个抽象基类,定义了策略接口execute。StrategyA和StrategyB是具体策略类,分别实现了execute方法。Context类持有一个策略对象,并通过execute_strategy方法调用策略的execute方法。- 通过
set_strategy方法,可以在运行时动态切换策略。
总结
策略模式通过将算法封装在独立的类中,使得算法可以独立于使用它的客户端而变化。这种模式非常适合在需要动态选择算法的场景中使用。