class Account(object):
def __init__(self,id,name,balance):
self.ID = id
self.name = name
self.__balance = balance
self.observers = set()
def __del__(self):
for ob in self.observers:
ob.close()
del self.observers
def register(self,observer):
self.observers.add(observer)
def unregister(self,observer):
self.observers.remove(observer)
def notify(self):
for ob in self.observers:
ob.update()
def withdraw(self,amt):
self.__balance -= amt
self.notify()
def getBalanceValue(self):
return self.__balance
import weakref
class AccountObserver(object):
accountDict = {}
def __init__(self, theaccount):
#self.accountref = weakref.ref(theaccount) # Create a weakref
theaccount.register(self)
if theaccount.ID not in AccountObserver.accountDict:
AccountObserver.accountDict[theaccount.ID]= weakref.ref(theaccount)
else:
print "Error>> Account Id conflict, please recheck it."
def __del__(self):
for id in AccountObserver.accountDict:
acc = AccountObserver.accountDict[id]() # Get account
if acc: # Unregister if still exists
acc.unregister(self)
def update(self):
for id in AccountObserver.accountDict:
if id:
print "ID=", id, ", Name=", AccountObserver.accountDict[id]().name, \
", Balance=", AccountObserver.accountDict[id]().getBalanceValue()
def close(self, id):
if id in AccountObserver.accountDict:
print "ID=", id, ", Account no longer in use"
acc = AccountObserver.accountDict[id]()
if acc:
acc.unregister(self)
del AccountObserver.accountDict[id]
def add(self, theAccount):
theAccount.register(self)
if theAccount.ID not in AccountObserver.accountDict:
AccountObserver.accountDict[theAccount.ID]= weakref.ref(theAccount)
else:
print "Error>> Account Id conflict, please recheck it."
a = Account(‘0001‘,‘Tom‘,1000.00)
b = Account(‘0002‘,‘Jimmy‘,2000.00)
a_ob = AccountObserver(a)
a_ob.update()
a_ob.add(b)
a_ob.update()
a_ob.close(‘0001‘)
a_ob.update()
b.withdraw(100)
a.withdraw(100)