def sceneOne(self): "Here is a case where a Context plays a Role by being part of a MoneyTransfer." self.balance = 1000 nested = MoneyTransfer(self, self.juliet) nested.transfer(self.balance) print self.juliet.name(), "is a rich girl with", self.juliet.balance, "ducats to her name." self.juliet.whereArtThou("romeo") self.romeo.lendMoneyFrom(self.juliet, 100)
def lendMoneyFrom(self, other, amount): """ Oh, that Romeo is such a deadbeat. Always lending money. Tsk. Incidentally shows a case where a Role kicks off a nested context. Note that this will fail if the Data Objects don't have a balance... """ print self.name(), "sayeth: 'Could thou lendeth me the pitiful sum of", amount, "ducats?'" nested = MoneyTransfer(other, self) nested.transfer(amount) print "'Oh, thank thee! I now have", self.balance, "lovely, shiny ducats to my name!"
# -------------------------------------------------- Data class Account(object): def __init__(self, amount): self.balance = amount super(Account, self).__init__() # -------------------------------------------------- MAIN if __name__ == '__main__': src = Account(1000) dst = Account(0) transferAmount = 100 print "Source account", src, "has a balance of", src.balance print "Destination account", dst, "has a balance of", dst.balance print "Transferring", transferAmount, "from source to destination." t = MoneyTransfer(src, dst) t.transfer(transferAmount) print "Source account", src, "now has a balance of", src.balance print "Destination account", dst, "now has a balance of", dst.balance print print "The following test shows that you can't use object equality" print "because an object is wrapped in a Role. However, for all other" print "purposes the Role base class does magic to make this wrapping" print "totally transparent." print print "Object equality?", dst == t.sink
""" DCI proof of concept Author: Serge Beaumont Created: 1 October 2008 Edit 4 dec 2011: Tidying up and changing names to true DCI naming. """ from moneytransfer import MoneyTransfer class Account(object): """An Account is a Domain object that represents any kind of account.""" def __init__(self): super(Account, self).__init__() self.balance = 0 if __name__ == '__main__': # Initialize the test case myAccount = Account() myAccount.balance = 1000 yourAccount = Account() print "Balance of my account: ", myAccount.balance print "Balance of your account: ", yourAccount.balance print "Transferring 200 money..." context = MoneyTransfer() context.transfer(myAccount, yourAccount, 200) print "Balance of my account: ", myAccount.balance print "Balance of your account: ", yourAccount.balance