-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsingleton.py
64 lines (49 loc) · 1.89 KB
/
singleton.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
"""
Singleton Design pattern is useful when we want to initialize the object only
once. This design pattern is useful when we need to share the object state
across the whole application.
If we try to re-instantiate the new object, it always provide the previously
initialized object instead of creating the one.
The best example of the singleton design pattern is a db connection pool.
In this case, if we want to connection to the database, trying to initialize
the db connection pool always returns the same object.
"""
from datetime import datetime
from time import sleep
class ConnectionPool:
_instance: "ConnectionPool"
created_at: float
name: str
def __init__(self) -> None:
self.created_at = datetime.now().timestamp()
self.name = ""
def __new__(cls):
if hasattr(cls, "_instance"):
print("Reusing old 'ConnectionPool' instance")
return cls._instance
print("Initializing new 'ConnectionPool' instance")
cls._instance = super(ConnectionPool, cls).__new__(cls)
return cls._instance
@classmethod
def _get_object(cls):
try:
return getattr(cls, "pool")
except AttributeError:
cls.pool = cls()
return cls.pool
if __name__ == "__main__":
pool1 = ConnectionPool() # Initializing new 'ConnectionPool' instance
sleep(2)
pool2 = ConnectionPool() # Reusing old 'ConnectionPool' instance
sleep(2)
pool3 = ConnectionPool() # Reusing old 'ConnectionPool' instance
"""
As the state of the singleton is shared across objects, changing one object
will update the state of all instantiated objects.
"""
print(pool1.created_at)
print(pool2.created_at) # created timestamp will be same
print(pool3.created_at) # created timestamp will be same
pool2.name = "Pool 2"
print(pool1.name) # Pool 2
print(pool3.name) # Pool 2