单例模式实现的几种方式
- 使用模块
- 使用__new__
- 使用装饰器
- 使用元类
使用模块
Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。
使用__new__
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls)
return cls._instance
s0 = Singleton()
s1 = Singleton()
print(id(s0))
print(id(s1))
使用装饰器
from functools import wraps
def singleton(cls):
instances = {}
@wraps(cls)
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances
return getinstance
@singleton
class Bar:
pass
b0 = Bar()
b1 = Bar()
print(id(b0))
print(id(b1))
使用元类
元类(metaclass)可以控制类的创建过程
class Singleton(type):
"""
元类继承type
"""
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super().__call__(*args, **kwargs)
return cls._instance
class Bar(metaclass=Singleton):
pass
b0 = Bar()
b1 = Bar()
print(id(b0))
print(id(b1))