- Learning Python Design Patterns(Second Edition)
- Chetan Giridhar
- 333字
- 2021-07-16 09:46:16
The Monostate Singleton pattern
We discussed the Gang of Four and their book in Chapter 1, Introduction to Design Patterns. GoF's Singleton design pattern says that there should be one and only one object of a class. However, as per Alex Martelli, typically what a programmer needs is to have instances sharing the same state. He suggests that developers should be bothered about the state and behavior rather than the identity. As the concept is based on all objects sharing the same state, it is also known as the Monostate pattern.
The Monostate pattern can be achieved in a very simple way in Python. In the following code, we assign the __dict__
variable (a special variable of Python) with the __shared_state
class variable. Python uses __dict__
to store the state of every object of a class. In the following code, we intentionally assign __shared_state
to all the created instances. So when we create two instances, 'b'
and 'b1'
, we get two different objects unlike Singleton where we have just one object. However, the object states, b.__dict__
and b1.__dict__
are the same. Now, even if the object variable x
changes for object b
, the change is copied over to the __dict__
variable that is shared by all objects and even b1
gets this change of the x
setting from one to four:
class Borg: __shared_state = {"1":"2"} def __init__(self): self.x = 1 self.__dict__ = self.__shared_state pass b = Borg() b1 = Borg() b.x = 4 print("Borg Object 'b': ", b) ## b and b1 are distinct objects print("Borg Object 'b1': ", b1) print("Object State 'b':", b.__dict__)## b and b1 share same state print("Object State 'b1':", b1.__dict__)
The following is the output of the preceding snippet:

Another way to implement the Borg pattern is by tweaking the __new__
method itself. As we know, the __new__
method is responsible for the creation of the object instance:
class Borg(object): _shared_state = {} def __new__(cls, *args, **kwargs): obj = super(Borg, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_state return obj
- Facebook Application Development with Graph API Cookbook
- Learning Java Functional Programming
- C語(yǔ)言程序設(shè)計(jì)(第3版)
- BeagleBone Media Center
- 新手學(xué)Visual C# 2008程序設(shè)計(jì)
- Hands-On C++ Game Animation Programming
- C++程序設(shè)計(jì)基礎(chǔ)教程
- Flux Architecture
- concrete5 Cookbook
- ASP.NET程序設(shè)計(jì)教程
- Linux C編程:一站式學(xué)習(xí)
- Mastering Python Design Patterns
- 編程改變生活:用Python提升你的能力(進(jìn)階篇·微課視頻版)
- OpenMP核心技術(shù)指南
- IPython Interactive Computing and Visualization Cookbook