Skip to content

Commit ea05e04

Browse files
committed
add Singleton pattern
1 parent a416a92 commit ea05e04

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

singleton/Singleton.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#
2+
# Python Design Patterns: Singleton
3+
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
4+
# 2016
5+
#
6+
# Source code is licensed under MIT License
7+
# (for more details see LICENSE)
8+
#
9+
10+
import sys
11+
12+
#
13+
# Singleton
14+
# has variable to hold one instance of the class and
15+
# method which gives us a way to instantiate the class
16+
#
17+
# reference: http://stackoverflow.com/questions/31875
18+
#
19+
class Singleton:
20+
def __init__(self, instance):
21+
self._instance = instance
22+
23+
def get(self):
24+
try:
25+
return self._only
26+
except AttributeError:
27+
self._only = self._instance()
28+
return self._only
29+
30+
def __call__(self):
31+
raise TypeError("...")
32+
33+
@Singleton
34+
class Class:
35+
def tell(self):
36+
print("This is singleton.")
37+
38+
39+
if __name__ == "__main__":
40+
singleton = Class.get()
41+
singleton.tell()

0 commit comments

Comments
 (0)