Monostate/Borg Singleton Design pattern
Singleton behavior can be implemented by Borg’s pattern but instead of having only one instance of the class, there are multiple instances that share the same state. Here we don’t focus on the sharing of the instance identity instead we focus on the sharing state.
# Singleton Borg pattern
class Borg:
# state shared by each instance
__shared_state = dict()
# constructor method
def __init__(self):
self.__dict__ = self.__shared_state
self.state = 'w3wiki'
def __str__(self):
return self.state
# main method
if __name__ == "__main__":
person1 = Borg() # object of class Borg
person2 = Borg() # object of class Borg
person3 = Borg() # object of class Borg
person1.state = 'DataStructures' # person1 changed the state
person2.state = 'Algorithms' # person2 changed the state
print(person1) # output --> Algorithms
print(person2) # output --> Algorithms
person3.state = 'Geeks' # person3 changed the
# the shared state
print(person1) # output --> Geeks
print(person2) # output --> Geeks
print(person3) # output --> Geeks
Output:
Algorithms
Algorithms
Geeks
Geeks
Geeks
Double Checked Locking Singleton Design pattern
It is easy to notice that once an object is created, the synchronization of the threading is no longer useful because now the object will never be equal to None and any sequence of operations will lead to consistent results.
So, when the object will be equal to None, then only we will acquire the Lock on the getInstance method.
# Double Checked Locking singleton pattern
import threading
class SingletonDoubleChecked(object):
# resources shared by each and every
# instance
__singleton_lock = threading.Lock()
__singleton_instance = None
# define the classmethod
@classmethod
def instance(cls):
# check for the singleton instance
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = cls()
# return the singleton instance
return cls.__singleton_instance
# main method
if __name__ == '__main__':
# create class X
class X(SingletonDoubleChecked):
pass
# create class Y
class Y(SingletonDoubleChecked):
pass
A1, A2 = X.instance(), X.instance()
B1, B2 = Y.instance(), Y.instance()
assert A1 is not B1
assert A1 is A2
assert B1 is B2
print('A1 : ', A1)
print('A2 : ', A2)
print('B1 : ', B1)
print('B2 : ', B2)
Output:
A1 : __main__.X object at 0x02EA2590
A2 : __main__.X object at 0x02EA2590
B1 : __main__.Y object at 0x02EA25B0
B2 : __main__.Y object at 0x02EA25B0
Singleton Method – Python Design Patterns
Prerequisite: Singleton Design pattern | Introduction