工厂模式(Factory Pattern)是一种常用的设计模式,用于创建对象时不会将客户端代码与类构造代码直接关联起来,而是通过一个共同的接口指向新创建的对象。这样可以在不修改客户端代码的情况下更改所创建的具体类实例。在Python中,实现工厂模式可以通过多种方式,包括简单工厂、工厂方法模式、抽象工厂模式等。
1. 简单工厂模式
简单工厂模式通常通过一个静态方法来创建对象,这个静态方法接收一个参数(通常是类名或其他标识符),然后根据这个参数返回相应的类实例。
class ProductA:
def operation(self):
return "Result of the Product A"
class ProductB:
def operation(self):
return "Result of the Product B"
class Factory:
@staticmethod
def get_product(product_type):
if product_type == "A":
return ProductA()
elif product_type == "B":
return ProductB()
else:
raise ValueError("Unsupported product type")
# 使用
productA = Factory.get_product("A")
print(productA.operation())
productB = Factory.get_product("B")
print(productB.operation())
2. 工厂方法模式
工厂方法模式将对象的创建延迟到子类中进行。工厂方法让类的实例化推迟到子类中进行。
class Product:
def operation(self):
pass
class ConcreteProductA(Product):
def operation(self):
return "Result of the ConcreteProduct A"
class ConcreteProductB(Product):
def operation(self):
return "Result of the ConcreteProduct B"
class Creator:
def factory_method(self):
raise NotImplementedError("Subclass must implement abstract method")
def an_operation(self):
product = self.factory_method()
return product.operation()
class ConcreteCreatorA(Creator):
def</