-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleTonMethod.py
47 lines (34 loc) · 1.01 KB
/
SingleTonMethod.py
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
# Double Checked Locking singleton pattern
import threading
class SingletonDoubleChecked(object):
# resources shared by each and every
# instance
__singleton_lock = threading.Lock()
__singleton_instance = None
# define the class method
@classmethod
def instance(cls):
# check for the singleton instance
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = cls()
# return the singleton instance
return cls.__singleton_instance
# main method
if __name__ == '__main__':
# create class X
class X(SingletonDoubleChecked):
pass
# create class Y
class Y(SingletonDoubleChecked):
pass
A1, A2 = X.instance(), X.instance()
B1, B2 = Y.instance(), Y.instance()
assert A1 is not B1
assert A1 is A2
assert B1 is B2
print('A1 : ', A1)
print('A2 : ', A2)
print('B1 : ', B1)
print('B2 : ', B2)