什么是單例模式
單例模式(也叫單件模式)的作用就是保證在整個應(yīng)用程序的生命周期中,任何一個時刻,單例類的實例都只存在一個(當(dāng)然也可以不存在)。
1 基于類 注意: 加鎖,否則多線程模式會報錯
import time,threading
class Foo(object):
lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls,*args,**kwargs):
if not hasattr(cls,'_instance'):
with Foo.lock:
if not hasattr(cls,'_instance'):
obj = cls(*args,**kwargs)
setattr(cls,'_instance',obj)
return cls._instance
def func(arg):
obj = Foo.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
2 . 基于new方法,也要加鎖,原理同上
import threading,time
class Singleton(object):
lock = threading.Lock()
def __init__(self):
time.sleep(1)
def __new__(cls, *args, **kwargs):
if not hasattr(cls,'_instance'):
with Singleton.lock:
if not hasattr(cls,'_instance'):
Singleton._instance = object.__new__(cls,*args,**kwargs)
return Singleton._instance
def task(args):
obj = Singleton()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=(i,))
t.start()
- 基于metaclass 加鎖,原理同上
class MyType(type):
lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls,'_instance'):
with MyType.lock:
if not hasattr(cls,'_instance'):
cls._instance = super(MyType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=MyType):
def __init__(self):
time.sleep(1)
def task():
obj = Foo()
print(obj)
for i in range(10):
t = threading.Thread(target=task,)
t.start()
總結(jié):單利模式存在的目的是保證當(dāng)前內(nèi)存中僅存在單個實例,避免內(nèi)存浪費,在Django admin的源碼中,就用到了單例模式?。?!