工厂设计模式的python代码
时间: 2023-10-12 19:13:23 浏览: 46
工厂设计模式的 Python 代码如下:
```python
class Product:
def operation(self):
pass
class ConcreteProduct1(Product):
def operation(self):
return "ConcreteProduct1"
class ConcreteProduct2(Product):
def operation(self):
return "ConcreteProduct2"
class Creator:
def factory_method(self):
pass
def some_operation(self):
product = self.factory_method()
result = f"Creator: The same creator's code has just worked with {product.operation()}"
return result
class ConcreteCreator1(Creator):
def factory_method(self):
return ConcreteProduct1()
class ConcreteCreator2(Creator):
def factory_method(self):
return ConcreteProduct2()
if __name__ == "__main__":
print("Client: Testing client code with the first creator...")
creator1 = ConcreteCreator1()
print(creator1.some_operation())
print("\n")
print("Client: Testing the same client code with the second creator...")
creator2 = ConcreteCreator2()
print(creator2.some_operation())
```
这里定义了一个 `Product` 基类,它包含了一个 `operation` 方法。`ConcreteProduct1` 和 `ConcreteProduct2` 是 `Product` 的具体实现。
`Creator` 是一个抽象类,它定义了一个 `factory_method` 的抽象方法和一个 `some_operation` 方法。`factory_method` 方法返回一个 `Product` 对象。`some_operation` 方法使用 `factory_method` 方法创建一个 `Product` 对象,并返回一个字符串。
`ConcreteCreator1` 和 `ConcreteCreator2` 继承自 `Creator`,分别实现了 `factory_method` 方法,用于创建 `ConcreteProduct1` 和 `ConcreteProduct2` 对象。在 `main` 函数中,我们测试了这两个具体的创建者类。