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

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
主站蜘蛛池模板: 龙门县| 博湖县| 察哈| 开阳县| 泸西县| 陈巴尔虎旗| 庆云县| 延寿县| 红河县| 迁西县| 平度市| 平定县| 阳山县| 察哈| 永泰县| 鄯善县| 巴彦县| 建宁县| 郁南县| 琼结县| 嘉鱼县| 浦北县| 屏东县| 龙井市| 鄄城县| 江西省| 始兴县| 博罗县| 桓台县| 芜湖市| 夏津县| 吉安市| 辽宁省| 芮城县| 五原县| 永平县| 九寨沟县| 宝鸡市| 石首市| 鸡西市| 阿坝|