工厂模式,给出示例代码
时间: 2024-04-10 11:25:02 浏览: 21
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需暴露对象的创建逻辑。工厂模式通过定义一个公共接口来创建对象,但允许子类决定实例化的类是哪一个。这样可以将对象的实例化延迟到子类中进行。
以下是一个简单的工厂模式示例代码:
```python
# 定义一个产品接口
class Product:
def operation(self):
pass
# 定义具体产品类A
class ConcreteProductA(Product):
def operation(self):
return "ConcreteProductA"
# 定义具体产品类B
class ConcreteProductB(Product):
def operation(self):
return "ConcreteProductB"
# 定义工厂类
class Factory:
def create_product(self, product_type):
if product_type == "A":
return ConcreteProductA()
elif product_type == "B":
return ConcreteProductB()
else:
raise ValueError("Invalid product type.")
# 使用工厂创建产品
factory = Factory()
product_a = factory.create_product("A")
print(product_a.operation()) # 输出:ConcreteProductA
product_b = factory.create_product("B")
print(product_b.operation()) # 输出:ConcreteProductB
```
在上述示例中,`Product` 是产品接口,`ConcreteProductA` 和 `ConcreteProductB` 是具体的产品类,它们都实现了 `operation` 方法。`Factory` 是工厂类,通过 `create_product` 方法根据传入的产品类型来创建相应的产品对象。