File tree 2 files changed +10
-6
lines changed
2 files changed +10
-6
lines changed Original file line number Diff line number Diff line change 1
1
class SingletonError (Exception ):
2
2
pass
3
3
4
+
4
5
class Singleton (type ):
5
6
_instances = {}
7
+
6
8
def __call__ (cls , * args , ** kwargs ):
7
9
if cls not in cls ._instances :
8
10
cls ._instances [cls ] = super (Singleton , cls ).__call__ (* args , ** kwargs )
9
11
return cls ._instances [cls ]
10
-
12
+
11
13
12
14
class ChocolateBoiler (metaclass = Singleton ):
13
15
def __init__ (self ) -> None :
14
16
self .empty = True
15
17
self .boiled = False
16
-
18
+
17
19
def fill (self ):
18
20
if not self .empty :
19
21
raise SingletonError
@@ -47,8 +49,5 @@ def chocolate_controller():
47
49
print (boiler2 is boiler )
48
50
49
51
50
-
51
- if __name__ == '__main__' :
52
+ if __name__ == "__main__" :
52
53
chocolate_controller ()
53
-
54
-
Original file line number Diff line number Diff line change
1
+ # Chapter 5: Singleton design pattern
2
+
3
+ ** Singleton** : ensures a class has only one instance, and provides a global point of access to it.
4
+
5
+ Based this [ stackoverflow post] ( https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python?noredirect=1&lq=1 ) .
You can’t perform that action at this time.
0 commit comments