
工厂模式是一种常用的设计模式,它可以将对象的创建和使用分离开来,使得代码更加灵活和可维护。在 Python
中,工厂模式有多种实现方式,下面我们来详细介绍一下。
1. 简单工厂模式
简单工厂模式是最基本的工厂模式,它通过一个工厂类来创建对象,客户端只需要知道要创建的对象的类型即可。下面是一个简单工厂模式的示例代码:
```python
class Product:
def show(self):
pass
class ProductA(Product):
def show(self):
print("ProductA")
class ProductB(Product):
def show(self):
print("ProductB")
class Factory:
def create_product(self, product_type):
if product_type == "A":
return ProductA()
elif product_type == "B":
return ProductB()
else:
return None
factory = Factory()
product_a = factory.create_product("A")
product_b = factory.create_product("B")
product_a.show() # Output: ProductA
product_b.show() # Output: ProductB
```
2. 工厂方法模式
工厂方法模式是在简单工厂模式的基础上进一步抽象,它将工厂类抽象成一个接口,每个具体的工厂类都实现这个接口来创建对象。下面是一个工厂方法模式的示例代码:
```python
class Product:
def show(self):
pass
class ProductA(Product):
def show(self):
print("ProductA")
class ProductB(Product):
def show(self):
print("ProductB")
class Factory:
def create_product(self):
pass
class FactoryA(Factory):
def create_product(self):
return ProductA()
class FactoryB(Factory):
def create_product(self):
return ProductB()
factory_a = FactoryA()
factory_b = FactoryB()
product_a = factory_a.create_product()
product_b = factory_b.create_product()
product_a.show() # Output: ProductA
product_b.show() # Output: ProductB
```
3. 抽象工厂模式
抽象工厂模式是在工厂方法模式的基础上进一步抽象,它将每个具体的工厂类抽象成一个工厂族,每个工厂族可以创建多个相关的对象。下面是一个抽象工厂模式的示例代码:
```python
class ProductA:
def show(self):
pass
class ProductB:
def show(self):
pass
class ProductA1(ProductA):
def show(self):
print("ProductA1")
class ProductA2(ProductA):
def show(self):
print("ProductA2")
class ProductB1(ProductB):
def show(self):
print("ProductB1")
class ProductB2(ProductB):
def show(self):
print("ProductB2")
class Factory:
def create_product_a(self):
pass
def create_product_b(self):
pass
class Factory1(Factory):
def create_product_a(self):
return ProductA1()
def create_product_b(self):
return ProductB1()
class Factory2(Factory):
def create_product_a(self):
return ProductA2()
def create_product_b(self):
return ProductB2()
factory1 = Factory1()
factory2 = Factory2()
product_a1 = factory1.create_product_a()
product_b1 = factory1.create_product_b()
product_a2 = factory2.create_product_a()
product_b2 = factory2.create_product_b()
product_a1.show() # Output: ProductA1
product_b1.show() # Output: ProductB1
product_a2.show() # Output: ProductA2
product_b2.show() # Output: ProductB2
```
以上就是 Python
中工厂模式的三种实现方式,它们分别是简单工厂模式、工厂方法模式和抽象工厂模式。在实际开发中,我们可以根据具体的需求选择合适的工厂模式来创建对象。