- 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
- 零基礎學Scratch少兒編程:小學課本中的Scratch創意編程
- PHP+MySQL網站開發技術項目式教程(第2版)
- The DevOps 2.4 Toolkit
- Oracle JDeveloper 11gR2 Cookbook
- Hands-On Natural Language Processing with Python
- ElasticSearch Cookbook(Second Edition)
- 移動互聯網軟件開發實驗指導
- Building Dynamics CRM 2015 Dashboards with Power BI
- 遠方:兩位持續創業者的點滴思考
- 零基礎學C語言(第4版)
- Secret Recipes of the Python Ninja
- Modernizing Legacy Applications in PHP
- Apache Solr PHP Integration
- Web前端開發技術:HTML、CSS、JavaScript
- Visual Basic語言程序設計上機指導與練習(第3版)