-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsingletonproxy.py
More file actions
45 lines (34 loc) · 984 Bytes
/
singletonproxy.py
File metadata and controls
45 lines (34 loc) · 984 Bytes
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
# -*- coding: utf-8 -*-
class Singleton:
"""
单例类装饰器,可以用于想实现单例的任何类。注意,不能用于多线程环境。
"""
def __init__(self, cls):
""" 需要的参数是一个类 """
self._cls = cls
def Instance(self):
"""
返回真正的实例
"""
try:
return self._instance
except AttributeError:
self._instance = self._cls()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `Instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
@Singleton
class A:
"""一个需要单列模式的类"""
def __init__(self):
pass
def display(self):
return id(self)
if __name__ == '__main__':
s1 = A.Instance()
s2 = A.Instance()
print(s1, s1.display())
print(s2, s2.display())
print(s1 is s2)