请列出5 种常见的设计模式,并挑选任一种设计模式用自己熟悉的代码实现
时间: 2023-04-09 09:03:31 浏览: 57
以下是五种常见的设计模式:
1. 工厂模式(Factory Pattern)
2. 单例模式(Singleton Pattern)
3. 观察者模式(Observer Pattern)
4. 装饰器模式(Decorator Pattern)
5. 策略模式(Strategy Pattern)
我选择实现工厂模式:
```python
class Animal:
def __init__(self, name):
self.name = name
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, name):
if animal_type == "dog":
return Dog(name)
elif animal_type == "cat":
return Cat(name)
else:
return None
animal_factory = AnimalFactory()
dog = animal_factory.create_animal("dog", "Buddy")
cat = animal_factory.create_animal("cat", "Fluffy")
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)