Liuw's Thinkpad

想要赢就先学会输,想要成功就先学会失败

Archive for the ‘borg’ tag

Borg Pattern in Python

without comments

During the search about Python singleton pattern, I discovered [ActiveState recipe 66531].

In this Borg Pattern, instances’ internal dictionary points to the same place, so all instances share the same state. Also, [Alex Martelli], the author of this recipe, has a interesting comment: Borg Pattern != Singleton Pattern. I admit that I confuse Borg Pattern with Singleton Pattern at first.

It’s NOT a singleton object… it doesn’t NEED to be! This is a completely and deeply different pattern from Singleton, and thus I find the latest comment totally off-base. Singleton focuses (wrongly) on object IDENTITY: that’s what the Gof4 focuses on, that’s what “EffC++” focuses on, etc, etc. But we don’t really care about identity most of the time, but about state and behavior.

The “Borg” design pattern IS quite possible in C++ (just a bit more laborious, but not much) and was indeed once written up in C++ Report (but I forget the name it was given then and can’t find my old issue): you get as many objects as you want, with separate identities but all sharing state and behavior. That’s the POINT! Just about all the practical USEFULNESS of Singleton without the troublesome identity-issue that Singleton tends to give.

Here’s the code, quite simple, cool.

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

Written by liuw

March 13th, 2010 at 11:35 pm

Posted in Programming,分享

Tagged with , ,