策略模式和工厂模式差别
时间: 2025-07-19 18:37:49 浏览: 4
### 策略模式与工厂模式的区别及使用场景
#### 设计分类
策略模式是一种行为型设计模式,其主要目的是定义一系列算法并将其封装起来,使它们可以互换使用而不影响客户端代码[^1]。相比之下,工厂模式属于创建型设计模式,专注于提供一种机制来创建对象,而无需指定具体的类实例化过程[^2]。
#### 主要功能
- **策略模式**的核心在于通过接口或抽象类定义一组可替换的行为逻辑,并允许这些行为在运行时动态切换。它关注的是如何让算法独立于使用它的客户程序之外变化[^1]。
- **工厂模式**的主要职责则是隐藏复杂对象的构建细节,简化对象获取的过程。简单工厂、工厂方法和抽象工厂是该模式下的三种常见形式,每种都有助于解决不同层次上的对象创建需求[^2]。
#### 使用场景对比
对于**策略模式**来说,在以下情况下尤为适用:
- 当存在多个相似但实现方式有所差异的操作时;
- 需要在不修改现有代码的前提下引入新的操作版本;
- 希望减少条件语句带来的耦合度,提高系统的灵活性和扩展性。
至于**工厂模式**,适合应用于如下场合:
- 创建的对象种类繁多且具有共同特征或者遵循统一接口的情况下;
- 对象的具体类型直到运行期间才能确定的时候;
- 想要将对象的构造逻辑集中管理以便维护更加方便高效的情形下[^2]。
```python
# 策略模式示例
from abc import ABC, abstractmethod
class Strategy(ABC):
@abstractmethod
def execute(self) -> str:
pass
class ConcreteStrategyA(Strategy):
def execute(self) -> str:
return "ConcreteStrategyA"
class Context:
def __init__(self, strategy: Strategy) -> None:
self._strategy = strategy
def set_strategy(self, strategy: Strategy) -> None:
self._strategy = strategy
def do_something(self) -> str:
return f"Context: {self._strategy.execute()}"
context = Context(ConcreteStrategyA())
print(context.do_something()) # 输出:Context: ConcreteStrategyA
# 工厂模式示例 - 抽象工厂
class Product(ABC):
@abstractmethod
def operation(self) -> str:
pass
class ConcreteProduct(Product):
def operation(self) -> str:
return "{Result of the ConcreteProduct}"
class Creator(ABC):
@abstractmethod
def factory_method(self) -> Product:
pass
def some_operation(self) -> str:
product = self.factory_method()
result = f"Creator: The same creator's code has just worked with {product.operation()}"
return result
class ConcreteCreator(Creator):
def factory_method(self) -> Product:
return ConcreteProduct()
creator = ConcreteCreator()
print(creator.some_operation()) # 输出:Creator: The same creator's code has just worked with {Result of the ConcreteProduct}
```
阅读全文
相关推荐




















