写出常用设计模式?并用代码实现一个比较擅长的设计模式
时间: 2024-03-20 10:37:25 浏览: 27
常用的设计模式有很多种,以下是其中几种比较常见的设计模式:
1. 单例模式(Singleton Pattern):
单例模式保证一个类只有一个实例,并提供一个全局访问点。以下是一个单例模式的示例代码:
```python
class Singleton:
__instance = None
@staticmethod
def get_instance():
if Singleton.__instance is None:
Singleton()
return Singleton.__instance
def __init__(self):
if Singleton.__instance is not None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self
```
2. 工厂模式(Factory Pattern):
工厂模式通过一个工厂类来创建对象,而不是直接使用new关键字。以下是一个工厂模式的示例代码:
```python
class Product:
def __init__(self, name):
self.name = name
class ProductFactory:
@staticmethod
def create_product(name):
return Product(name)
# 使用工厂创建对象
product = ProductFactory.create_product("example")
```
3. 观察者模式(Observer Pattern):
观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。以下是一个观察者模式的示例代码:
```python
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def detach(self, observer):
self.observers.remove(observer)
def notify(self):
for observer in self.observers:
observer.update()
class Observer:
def update(self):
print("Observer is notified!")
# 创建主题和观察者
subject = Subject()
observer = Observer()
# 将观察者添加到主题中
subject.attach(observer)
# 主题状态改变,通知观察者
subject.notify()
```
以上是三种常见的设计模式的示例代码。
相关推荐
![](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)