Python中的单例模式
单例模式的三个要点
- 单例类只能创建一个实例
- 单例类自己创建自己唯一的实例
- 单例类给其他所有对象提供实例
单例模式的实现
-
导入模块
-
使用装饰器
from functools import wraps def singleton(cls): instance = {} @wraps(cls) def wrapper(*args,**kwargs): if cls not in instance: instance[cls] = cls(*args,**kwargs) return instance[cls] return wrapper @singleton class Test(object): def __init__(self,x): self.x = x test1 = Test(1) test2 = Test(2) -
使用类
class Singleton(object): def __init__(self,x): self.x = x @classmethod def instance(cls,*args,**kwargs): if not hasattr(Singleton,'instance'): Singleton.instance = Singleton(*args,**kwargs) return Singleton.instance test = Singleton() -
使用_ _ new_ _
import threading import time class Singleton(object): insatnce = None lock = threading.Rlock() def __init__(self,name): self.name = name def __new__(cls,*args,**kwargs): with cls.lock: if not cls.instance: cls.instance = object.__new__(cls) return cls.instance def func(): obj = Singleton("zevin") print(obj) for i in range(10): t= threading.Thread(target=func) t.start()

浙公网安备 33010602011771号