策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理
时间: 2024-08-15 19:05:38 浏览: 35
### 策略模式简介
**策略模式** 是一种行为设计模式,在软件开发中用于解决算法选择的问题。这种模式允许动态地决定应该采用哪个具体算法来执行任务,从而提高了程序的灵活性和可扩展性。
#### 定义:
- **角色**:
- 抽象策略(`Strategy`):定义了一组算法接口,这些接口被所有具体的策略类所继承或实现。
- 具体策略(`ConcreteStrategy`):实现了抽象策略接口的具体算法。
- 上下文(`Context`):持有并使用策略对象,负责调用具体策略的方法以执行相应的算法。
- **核心思想**:
- 将一组相关的算法组织在一起,形成一个策略族。
- 通过上下文对象来切换不同具体策略对象,从而改变算法的行为而无需修改上下文类的代码。
#### 示例代码:
假设我们有一个上下文类 `PaymentProcessor` 负责处理支付方式的选择,我们可以利用策略模式实现这个功能:
```python
from abc import ABC, abstractmethod
# 抽象策略接口
class PaymentStrategy(ABC):
@abstractmethod
def process_payment(self, amount):
pass
# 具体策略 A
class CreditCardStrategy(PaymentStrategy):
def process_payment(self, amount):
return f"Processing payment of {amount} using credit card."
# 具体策略 B
class PayPalStrategy(PaymentStrategy):
def process_payment(self, amount):
return f"Processing payment of {amount} using PayPal."
# 下文/环境类
class PaymentProcessor:
def __init__(self, strategy):
self._strategy = strategy
def set_strategy(self, strategy):
self._strategy = strategy
def get_payment_info(self, amount):
return self._strategy.process_payment(amount)
if __name__ == "__main__":
processor = PaymentProcessor(CreditCardStrategy())
print(processor.get_payment_info(100))
# 改变策略到 PayPal
processor.set_strategy(PayPalStrategy())
print(processor.get_payment_info(150))
```
### 相关问题:
1. 如何在策略模式中添加新的支付策略而不修改现有的代码结构?
2. 在什么场景下更适合使用策略模式而不是其他设计模式?
3. 策略模式与责任链模式有何区别?