Monday, July 5, 2010

Still use singleton? There's another choice in python: Borg design pattern

Few months ago i implemented a db extension for my own python web framework, which supports different database backend. To prevent it from creating multiple instance of db-connection i have chosen singleton design pattern as usual. But after spent some time on google i found another interesting design pattern Borg. It's done this job as good as singleton. Let's take a look of this magical pattern:

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
OK, that's it. Have fun.