来一段工厂设计模式得代码
时间: 2023-01-31 14:05:07 浏览: 65
工厂设计模式是一种常见的软件设计模式,它提供了一种方法来创建对象,而不必直接指定要创建哪个类的对象。这样,可以在运行时动态地创建对象,并且可以隐藏具体类的实现细节。
这里是一个使用工厂设计模式的示例代码:
```
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
elif animal_type == "bird":
return Bird()
else:
raise ValueError("Invalid animal type")
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Bird:
def speak(self):
return "Tweet!"
# usage example
factory = AnimalFactory()
animal = factory.create_animal("dog")
animal.speak() # Output: "Woof!"
```
在这个示例中,我们定义了一个 `AnimalFactory` 类,它有一个 `create_animal` 方法,用于根据给定的动物类型创建对应的对象。然后我们定义了三种动物类:`Dog`、`Cat` 和 `Bird`,每种类都有一个 `speak` 方法,用于返回动物的叫声。
我们可以使用工厂设计模式动态地创建动物对象,而不必关心具体的实现细节。例如,在上面的代码中,我们可以使用工厂创建一只狗,并调用它的 `speak` 方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)