c++工厂模式的代码实例
时间: 2023-10-18 21:06:51 浏览: 39
工厂模式是一种创建型模式,它提供了一种创建对象的最佳方式。以下是一个简单的工厂模式实现示例:
```python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "Dog":
return Dog()
elif animal_type == "Cat":
return Cat()
else:
return None
factory = AnimalFactory()
dog = factory.create_animal("Dog")
cat = factory.create_animal("Cat")
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
```
在上面的示例中,我们定义了一个 `Animal` 基类和两个继承自它的子类 `Dog` 和 `Cat`。然后,我们定义了一个工厂类 `AnimalFactory`,它负责根据传递给它的参数来创建相应的对象。
最后,我们实例化了工厂类,通过调用 `create_animal()` 方法来创建 `Dog` 和 `Cat` 对象,并通过调用它们的 `speak()` 方法来输出它们的声音。
这就是一个简单的工厂模式实现示例。