将单例模式拓展成多例模式
时间: 2023-05-27 17:02:33 浏览: 61
多例模式,也叫对象池模式,是一种创建型模式,它允许我们在需要时创建有限数量的实例,并在使用完毕后将其放回池中,以便其他使用者可以继续使用。
下面是一个简单的多例模式的实现:
```python
class ObjectPool:
_instances = []
_max_instances = 5
def __init__(self):
if len(self._instances) >= self._max_instances:
raise Exception("Too many instances!")
self._instances.append(self)
@classmethod
def get_instance(cls):
if not cls._instances:
for _ in range(cls._max_instances):
cls._instances.append(cls())
return cls._instances.pop(0)
def release(self):
self._instances.append(self)
def do_something(self):
print("Do something.")
```
在这个实现中,我们使用类变量`_instances`来保存所有实例,并使用类方法`get_instance()`来获取一个空闲的实例。如果没有空闲的实例,我们就创建新的实例,并将其添加到`_instances`中,然后返回这个实例。我们还定义了`release()`方法,用于将实例返回给池中。
现在,我们可以使用`ObjectPool`类来创建多个实例:
```python
o1 = ObjectPool.get_instance()
o2 = ObjectPool.get_instance()
o1.do_something()
o2.do_something()
o1.release()
o2.release()
```
这里,我们从池中获取两个实例`o1`和`o2`,然后调用它们的`do_something()`方法。当我们使用完它们后,我们使用`release()`方法将它们返回给池中。注意,我们最多只能创建5个`ObjectPool`实例,因为我们在类变量`_max_instances`中限制了实例的数量。
这样,我们就成功将单例模式拓展成了多例模式。