單例模式
單例模式是常見的軟件設(shè)計(jì)模式伪冰,該模式主要目的確保某一個(gè)類只能有一個(gè)實(shí)例存在
1基于類注意:加鎖否則多線程模式會(huì)報(bào)錯(cuò)
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()
3基于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()
4使用模塊,python模塊就是天然的單例模式攻晒,因?yàn)槟K在第一次導(dǎo)入時(shí)會(huì)生成.pyc文件
1建立一個(gè)mysingleton的py文件
class my_Singleton(object):
def foo(self)
pass
my_singleton=my_Singleton()
將上面的代碼保存在文件mysingleton.py中然后這樣使用
from mysingleton import my_singleton
my_singleton.foo()