Using Borg to instead of singleton in Python

2012年10月24日 星期三

Using Borg to instead of singleton in Python


上篇有說到可以使用singleton方式,當多個物件同時對一個資源做修改時,不會造成race condition,這篇將繼續介紹另一種更方便的方式 Borg



def borg(cls):
    cls._state = {}
    orig_init = cls.__init__
    def new_init(self, *args, **kwargs):
        self.__dict__ = cls._state
        orig_init(self, *args, **kwargs)
    cls.__init__ = new_init
    return cls

class animal(object):
    def __init__(self,name):
        self.name = name

    def assign_count(self):
        self.count = 0

    def pringInfo(self):
        self.count = self.count + 1
        print "%s appear %s times"%(self.name,self.count)

animal = borg(animal)

if __name__ == '__main__':
    b1 = animal("dog")
    b1.assign_count()
    b1.pringInfo()
    b2 = animal("cat")
    b2.pringInfo()


執行結果:

root@ubuntu:/mnt/test# python borg.py
dog appear 1 times
cat appear 2 times
cat appear 3 times




0 意見 :

張貼留言