8.2. Borg

  • EN: Borg

  • PL: Borg

  • Type: object

The Borg design pattern, also known as the Monostate pattern, is a design pattern that ensures all instances of a class share the same state. In Python, this is typically implemented using a shared dictionary.

Here's a simple example of the Borg pattern in Python:

>>> class Borg:
...     _shared_state = {}
...     def __init__(self):
...         self.__dict__ = self._shared_state
>>> class ChildBorg(Borg):
...     pass
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1.x = 4
>>> print(b2.x)
>>> b3 = ChildBorg()
>>> print(b3.x)

In this example, Borg is a class that has a class attribute _shared_state which is a dictionary. This dictionary is assigned to the instance dictionary in the __init__ method. Therefore, when an attribute is set in one instance, it is available in all instances. ChildBorg is a subclass of Borg and it shares the same state as its parent class.

The real reason that borg is different comes down to subclassing. If you subclass a borg, the subclass' objects have the same state as their parents classes objects, unless you explicitly override the shared state in that subclass. Each subclass of the singleton pattern has its own state and therefore will produce different objects. Also in the singleton pattern the objects are actually the same, not just the state (even though the state is the only thing that really matters). [1]

8.2.1. Pattern


8.2.2. Problem


8.2.3. Solution


class Borg:
    shared_state: dict = {}

    def __init__(self):
        self.__dict__ = self.shared_state

8.2.4. References