一、装饰器模式
def singleton(cls, *args, **kwargs):
instance = {}
def _singleton():
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return _sigleton
@singleton
class Test(object):
a = 1
test = Test()
test1 = Test()
print(id(test) == id(test1))
>>> True
二、使用new方法
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kargs)
return cls._instance
class Test(Singleton):
a = 1
test = Test()
test1 = Test()
print(id(test) == id(test1))
>>> True
三、共享dict方法
class Singleton(object):
_state = {}
def __new__(cls, *args, **kwargs):
obj = super(Singleton, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = obj._state
return obj
class Test(Singleton):
a = 1
test = Test()
test1 = Test()
print(id(test) == id(test1))
print(id(test.__dict__) == id(test1.__dict__))
>>> False
>>> True
四、import导入
# a.py
class Test(object):
a = 1
test = Test()
# b.py
from a import test
print(id(test))
# c.py
from a import test
print(id(test))