官术网_书友最值得收藏!

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
主站蜘蛛池模板: 上杭县| 上高县| 剑河县| 弥勒县| 自贡市| 柘城县| 高阳县| 聊城市| 綦江县| 张家口市| 新竹市| 梁河县| 大丰市| 渭南市| 浙江省| 广水市| 大理市| 河曲县| 江安县| 宜春市| 瓮安县| 会宁县| 西盟| 巴林左旗| 内黄县| 靖安县| 滁州市| 余干县| 南城县| 鸡东县| 盘锦市| 海淀区| 府谷县| 新沂市| 彭山县| 商水县| 镶黄旗| 华坪县| 浠水县| 平定县| 鹤峰县|