-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathsingleton.py
40 lines (30 loc) · 918 Bytes
/
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
"""
Singleton
- A component which is instantiated only once
Motivation
- For some components it only makes sense to have one in the system
- Database repository
- Object factory
- E.g., the initializer call is expensive
- We only do it once
- We provide everyone with the same instance
- Want to prevent anyone from creating additional copies
- Need to take care of lazy instantiation
"""
import random
class Database:
_instance = None
def __init__(self):
id = random.randint(1, 101)
print('Loading database from file')
print(f'id = {id}')
# redefine allocator
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Database, cls)\
.__new__(cls, *args, **kwargs)
return cls._instance
D1 = Database()
D2 = Database()
print(D1 == D2)
# approach is not good enough, initializer still gets called