File tree Expand file tree Collapse file tree 2 files changed +35
-14
lines changed Expand file tree Collapse file tree 2 files changed +35
-14
lines changed Original file line number Diff line number Diff line change @@ -4,3 +4,5 @@ __pycache__
4
4
* .egg-info /
5
5
.tox /
6
6
venv
7
+ .vscode /
8
+ .python-version
Original file line number Diff line number Diff line change 25
25
https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py
26
26
27
27
*References:
28
- https://fkromer.github.io/python-pattern-references/design/#singleton
28
+ - https://fkromer.github.io/python-pattern-references/design/#singleton
29
+ - https://learning.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html
30
+ - http://www.aleax.it/5ep.html
29
31
30
32
*TL;DR
31
33
Provides singleton-like behavior sharing state between instances.
32
34
"""
33
35
34
36
35
37
class Borg :
36
- __shared_state = {}
38
+ _shared_state = {}
37
39
38
40
def __init__ (self ):
39
- self .__dict__ = self .__shared_state
40
- self .state = 'Init'
41
-
42
- def __str__ (self ):
43
- return self .state
41
+ self .__dict__ = self ._shared_state
44
42
45
43
46
44
class YourBorg (Borg ):
47
- pass
48
45
46
+ def __init__ (self , state = None ):
47
+ super ().__init__ ()
48
+ if state :
49
+ self .state = state
50
+ else :
51
+ # initiate the first instance with default state
52
+ if not hasattr (self , 'state' ):
53
+ self .state = 'Init'
54
+
55
+ def __str__ (self ):
56
+ return self .state
57
+
49
58
50
59
def main ():
51
60
"""
52
- >>> rm1 = Borg ()
53
- >>> rm2 = Borg ()
61
+ >>> rm1 = YourBorg ()
62
+ >>> rm2 = YourBorg ()
54
63
55
64
>>> rm1.state = 'Idle'
56
65
>>> rm2.state = 'Running'
@@ -73,15 +82,25 @@ def main():
73
82
>>> rm1 is rm2
74
83
False
75
84
76
- # Shared state is also modified from a subclass instance `rm3`
85
+ # New instances also get the same shared state
77
86
>>> rm3 = YourBorg()
78
87
79
88
>>> print('rm1: {0}'.format(rm1))
80
- rm1: Init
89
+ rm1: Zombie
81
90
>>> print('rm2: {0}'.format(rm2))
82
- rm2: Init
91
+ rm2: Zombie
92
+ >>> print('rm3: {0}'.format(rm3))
93
+ rm3: Zombie
94
+
95
+ # A new instance can explicitly change the state during creation
96
+ >>> rm4 = YourBorg('Running')
97
+
98
+ >>> print('rm4: {0}'.format(rm4))
99
+ rm4: Running
100
+
101
+ # Existing instances reflect that change as well
83
102
>>> print('rm3: {0}'.format(rm3))
84
- rm3: Init
103
+ rm3: Running
85
104
"""
86
105
87
106
You can’t perform that action at this time.
0 commit comments