Skip to content

Commit 3bf38c5

Browse files
Singleton Patterns
1 parent 48ee39a commit 3bf38c5

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import random
2+
3+
class Database:
4+
initialized = False
5+
6+
def __init__(self):
7+
# self.id = random.randint(1,101)
8+
# print('Generated an id of ', self.id)
9+
# print('Loading database from file')
10+
pass
11+
12+
_instance = None
13+
14+
def __new__(cls, *args, **kwargs):
15+
if not cls._instance:
16+
cls._instance = super(Database, cls)\
17+
.__new__(cls, *args, **kwargs)
18+
19+
return cls._instance
20+
21+
22+
database = Database()
23+
24+
if __name__ == '__main__':
25+
d1 = Database()
26+
d2 = Database()
27+
28+
print(d1.id, d2.id)
29+
print(d1 == d2)
30+
print(database == d1)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def singleton(class_):
2+
instances = {}
3+
4+
def get_instance(*args, **kwargs):
5+
if class_ not in instances:
6+
instances[class_] = class_(*args, **kwargs)
7+
return instances[class_]
8+
9+
return get_instance
10+
11+
12+
@singleton
13+
class Database:
14+
def __init__(self):
15+
print('Loading database')
16+
17+
18+
if __name__ == '__main__':
19+
d1 = Database()
20+
d2 = Database()
21+
print(d1 == d2)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Singleton(type):
2+
""" Metaclass that creates a Singleton base type when called. """
3+
_instances = {}
4+
5+
def __call__(cls, *args, **kwargs):
6+
if cls not in cls._instances:
7+
cls._instances[cls] = super(Singleton, cls)\
8+
.__call__(*args, **kwargs)
9+
return cls._instances[cls]
10+
11+
12+
class Database(metaclass=Singleton):
13+
def __init__(self):
14+
print('Loading database')
15+
16+
17+
if __name__ == '__main__':
18+
d1 = Database()
19+
d2 = Database()
20+
print(d1 == d2)

0 commit comments

Comments
 (0)