python单例的四种实现方式(线程安全)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from threading import Lock
from functools import wraps
def (func):
func.__lock__ = Lock()
def acquire_lock(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return acquire_lock
class Singleton1(object):
"""使用new方法"""
@thread_safety
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super(Singleton1, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
class Singleton2(object):
"""使用相同属性"""
_state = {}
@thread_safety
def __new__(cls, *args, **kwargs):
instance = super(Singleton2, cls).__new__(cls, *args, **kwargs)
instance.__dict__ = cls._state
return instance
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
def singleton(cls):
instances = {}
@wraps(cls)
@thread_safety
def _singleton(*args, **kwargs):
"""使用装饰器"""
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Singleton3(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
if __name__ == '__main__':
s1 = Singleton1()
s2 = Singleton1()
s3 = Singleton2()
s3.name = "jordan"
s4 = Singleton2()
s5 = Singleton3(123)
s6 = Singleton3(456)
print(s1, s2, s1 is s2)
print(s3, s4, s3 is s4, s3.name is s4.name)
print(s5, s6, s5 is s6)

输出结果:

1
2
3
> (类Singleton1的实例对象id:140151665159696, 类Singleton1的实例对象id:140151665159696, True)
> (类Singleton2的实例对象id:140151665159760, 类Singleton2的实例对象id:140151665159824, False, True)
> (类Singleton3的实例对象id:140151665159888, 类Singleton3的实例对象id:140151665159888, True)