Using Borg to instead of singleton in Python
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