单例模式、工厂模式、代理模式、适配模式怎么写
时间: 2023-09-30 15:11:47 浏览: 127
代理模式、单例模式、工厂模式实例代码
以下是四种设计模式的示例代码:
## 单例模式(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
```
## 工厂模式(Factory Pattern)
工厂模式通过创建一个工厂来创建对象,而不是直接实例化对象。
```python
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
class AnimalFactory:
@staticmethod
def create_animal(kind, name):
if kind == "dog":
return Dog(name)
elif kind == "cat":
return Cat(name)
else:
return None
```
## 代理模式(Proxy Pattern)
代理模式为其他对象提供一种代理以控制对该对象的访问。
```python
class Subject:
def request(self):
pass
class RealSubject(Subject):
def request(self):
print("RealSubject: Handling request.")
class Proxy(Subject):
def __init__(self, real_subject):
self._real_subject = real_subject
def request(self):
if self.check_access():
self._real_subject.request()
self.log_access()
def check_access(self):
print("Proxy: Checking access prior to firing a real request.")
return True
def log_access(self):
print("Proxy: Logging the time of request.")
```
## 适配器模式(Adapter Pattern)
适配器模式用于将一个类的接口转换为另一个类的接口。
```python
class Target:
def request(self):
pass
class Adaptee:
def specific_request(self):
return "Adaptee: Specific request."
class Adapter(Target):
def __init__(self, adaptee):
self._adaptee = adaptee
def request(self):
return f"Adapter: (TRANSLATED) {self._adaptee.specific_request()}"
```
阅读全文