1.單例模式要點
- 某個類只有一個實例;
- 類必須自行創建實例
- 必須自行向系統提供這個實例
2.實現單例模式方法
- 使用模塊
- 使用__new__
- 使用裝飾器(decorator)
- 使用元類(metaclass)
3.模塊
一:將類保存到test1.py文件中
#test1.py
class Opt(object):
def foo(self):
print("hello")
my_opt = Opt()
二:獲取一個單例對象
from .test1 import my_opt
my_opt.foo()
4.使用__new__
說明:__init__和__new__的區別,__init__是類實例初始化的時候調用的,__new__是類創建實例的時候調用的,故而可以使用__new__來創建單例模式。
class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls, '_instance'):
cls._instance = Super(Singleton,cls).__new__(cls,*args,**kwargs)
return cls._instance