工厂方法模式
工厂方法模式
工厂方法模式(Factory Method Pattern)是一种创建型设计模式,它定义了一个创建对象的接口,但由子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。
工厂方法模式的特点
- 定义创建对象的接口:客户端使用接口创建对象,而无需知道具体的类。
- 子类决定实例化的具体类:通过子类的实现,决定实例化哪个具体类。
- 松耦合:将对象的创建与使用分离,提高代码的灵活性和可维护性。
工厂方法模式的结构
- 产品(Product):定义了工厂方法所创建对象的接口。
- 具体产品(ConcreteProduct):实现了产品接口。
- 工厂(Creator):声明了返回产品对象的工厂方法。
- 具体工厂(ConcreteCreator):实现了工厂方法,返回具体产品实例。
工厂方法模式的Python实现
以下是工厂方法模式在Python中的一个实现示例:
1. 定义产品接口和具体产品类
from abc import ABC, abstractmethod
# 产品接口
class Product(ABC):
@abstractmethod
def operation(self) -> str:
pass
# 具体产品A
class ConcreteProductA(Product):
def operation(self) -> str:
return "Result of ConcreteProductA"
# 具体产品B
class ConcreteProductB(Product):
def operation(self) -> str:
return "Result of ConcreteProductB"
2. 定义工厂接口和具体工厂类
# 工厂接口
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
# 具体工厂A
class ConcreteCreatorA(Creator):
def factory_method(self) -> Product:
return ConcreteProductA()
# 具体工厂B
class ConcreteCreatorB(Creator):
def factory_method(self) -> Product:
return ConcreteProductB()
3. 客户端代码
def client_code(creator: Creator) -> None:
print(f"Client: I'm not aware of the creator's class, but it still works.\n"
f"{creator.some_operation()}")
if __name__ == "__main__":
print("App: Launched with ConcreteCreatorA.")
client_code(ConcreteCreatorA())
print("\n")
print("App: Launched with ConcreteCreatorB.")
client_code(ConcreteCreatorB())
运行结果
App: Launched with ConcreteCreatorA.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with Result of ConcreteProductA
App: Launched with ConcreteCreatorB.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with Result of ConcreteProductB
说明
- 产品接口(Product):定义了具体产品所需的接口(
operation
方法)。 - 具体产品(ConcreteProductA 和 ConcreteProductB):实现了产品接口,提供具体产品的实现。
- 工厂接口(Creator):声明了工厂方法(
factory_method
),并实现了一些依赖产品对象的操作(some_operation
)。 - 具体工厂(ConcreteCreatorA 和 ConcreteCreatorB):实现了工厂方法,实例化并返回具体产品。
通过工厂方法模式,可以在不修改现有代码的情况下,通过子类化来引入新的产品类,实现了代码的开放-封闭原则(Open/Closed Principle)。