-
Notifications
You must be signed in to change notification settings - Fork 4
/
singletonpattern.py
103 lines (80 loc) · 2.68 KB
/
singletonpattern.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 1. EAGER INITIALIZATION METHOD
class DBConnection_1:
_con_object = None
def __new__(cls):
if cls._con_object is None:
cls._con_object = super(DBConnection_1, cls).__new__(cls)
return cls._con_object
def __init__(self):
pass
@staticmethod
def get_instance():
return DBConnection_1._con_object
# 2. LAZY INITIALIZATION METHOD
class DBConnection_2:
_con_object = None
def __init__(self):
pass
@staticmethod
def get_instance():
if DBConnection_2._con_object is None:
DBConnection_2._con_object = DBConnection_2()
return DBConnection_2._con_object
# 3. EAGER AND LAZY INITIALIZATION WITH THREAD SAFETY (DOUBLE LOCKING)
import threading
class DBConnection_3:
_con_object = None
_lock = threading.Lock()
def __new__(cls):
if cls._con_object is None:
with cls._lock:
if cls._con_object is None:
cls._con_object = super(DBConnection_3, cls).__new__(cls)
return cls._con_object
def __init__(self):
pass
@staticmethod
def get_instance():
return DBConnection_3._con_object
class DBConnection_4:
_con_object = None
_lock = threading.Lock()
def __init__(self):
pass
@staticmethod
def get_instance():
if DBConnection_4._con_object is None:
with DBConnection_4._lock:
if DBConnection_4._con_object is None:
DBConnection_4._con_object = DBConnection_4()
return DBConnection_4._con_object
if __name__ == "__main__":
con_object_1 = DBConnection_1.get_instance()
con_object_2 = DBConnection_1.get_instance()
print(f"Instance ID: {id(con_object_1)}")
print(f"Instance ID: {id(con_object_2)}")
con_object_1 = DBConnection_2.get_instance()
con_object_2 = DBConnection_2.get_instance()
print(f"Instance ID: {id(con_object_1)}")
print(f"Instance ID: {id(con_object_2)}")
def test_singleton_3():
singleton = DBConnection_3.get_instance()
print(f"Instance ID: {id(singleton)}")
def test_singleton_4():
singleton = DBConnection_4.get_instance()
print(f"Instance ID: {id(singleton)}")
# Create multiple threads to test thread safety
threads = []
for i in range(5):
thread = threading.Thread(target=test_singleton_3)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
threads = []
for i in range(5):
thread = threading.Thread(target=test_singleton_4)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()