Python工厂模式
时间: 2023-12-15 10:32:36 浏览: 28
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在Python中,工厂模式通常使用工厂方法实现。当用户调用一个方法时,我们传入一个字符串,返回值作为一个新对象是通过工厂方法实现的。工厂方法中使用的对象类型由通过方法传递的字符串确定。
以下是一个简单的Python工厂模式的例子:
```python
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return "Woof!"
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return "Meow!"
def get_pet(pet="dog"):
pets = dict(dog=Dog("Hope"), cat=Cat("Peace"))
return pets[pet]
d = get_pet("dog")
print(d.speak()) # 输出:Woof!
c = get_pet("cat")
print(c.speak()) # 输出:Meow!
```
在上面的例子中,我们定义了两个类Dog和Cat,它们都有一个speak()方法。然后我们定义了一个get_pet()函数,它接受一个字符串参数pet,根据pet的值返回一个新的对象。最后,我们使用get_pet()函数创建了一个Dog对象和一个Cat对象,并调用它们的speak()方法。