1. 装饰器单例模式(推荐使用)
# -------------------- 装饰器----单例
def cls_foo(cls):
_instance = {}
def wrap(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return wrap
@cls_foo
class Stu:
def __init__(self, name):
self.name = name
s1 = Stu('小娃')
s2 = Stu('小l')
print(id(s1), id(s2))
new中的方法单例,满足线程安全
# -------------------new 方法中的单例
import threading
class School:
_threading_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(School, '_instance'):
with School._threading_lock:
if not hasattr(School, '_instance'):
School._instance = (School,cls).__new__(cls,*args,**kwargs)
return School._instance
def __init__(self, name):
self.name = name
d1 = School('彭男')
d2 = School('成都')
print(d1, d2)