Why is the Borg pattern better than the Singleton pattern in Python

Viewed 34352

Why is the Borg pattern better than the Singleton pattern?

I ask because I don't see them resulting in anything different.

Borg:

class Borg:
  __shared_state = {}
  # init internal state variables here
  __register = {}
  def __init__(self):
    self.__dict__ = self.__shared_state
    if not self.__register:
      self._init_default_register()

Singleton:

class Singleton:
  def __init__(self):
    # init internal state variables here
    self.__register = {}
    self._init_default_register()

# singleton mechanics external to class, for example this in the module
Singleton = Singleton()

What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).

And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat init as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.

It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.

6 Answers

Also, Borg-like pattern allows users of the class to choice if they want to share the state or create a separate instance. (whether or not this may be a good idea is a separate topic)

class MayBeBorg:
    __monostate = None

    def __init__(self, shared_state=True, ..):
        if shared_state:

            if not MayBeBorg.__monostate:
                MayBeBorg.__monostate = self.__dict__
            else:
                self.__dict__ = MayBeBorg.__monostate
                return
        self.wings = ..
        self.beak = ..
Related