Python 单例模式实现方法
1.模块化
# Python 的模块天然就是单例模式
# 模块在第一次被导入时会生成.pyc文件,第二次导入时会直接加载.pyc文件 而不会再次执行模块中的的代码,所以我们可以这样来实现单例模式
# test.py
class A(object):
def __init__(self, name):
self.name = name
t = A(treasure)
# test1.py
from test import t # 这里引入的就是我们单例模式的对象
2.使用装饰器
def test(cls):
_instance = {}
def _sing(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return _sing
@test
class A(object):
a = 1
def __init__(self, x):
self.x = x
a1 = A(2)
a2 = A(3)
# 打印可知a1, a2 两个对象的内存地址是一样的, 并且a2.x为2
3.基于 _new__方法
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls)
return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)