13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

IntegrationFor a MoneySum to truly be an Impostor for a Money, it has to support all the same messages. Allthe combinations of Moneys and MoneySums have to work together. We will use Double Dispatchto implement this. Double Dispatch states: “Send a message to the argument. Append the classname of the receiver to the selector. Pass the receiver as an argument.” Money addition becomes:Money>> + aMoney^aMoney addMoney: selfThe old Money>>+ becomes Money>>addMoney:Money>>addMoney: aMoney^currency = aMoney currencyifTrue:[self speciesamount: amount + aMoney amountcurrency: currency]ifFalse:[MoneySum monies: (Arraywith: selfwith: aMoney)]MoneySum arithmetic follows the Double Dispatch pattern, too:MoneySum>> + aMoney^aMoney addMoneySum: selfIf a MoneySum is adding a Money, it should produce a new MoneySum with the Money added tothe list of Monies:MoneySum>>addMoney: aMoney^self species monies: (monies copyWith: aMoney)Now we can send “+” to a Money with a MoneySum as argument:| m1 m2 |m1 := Moneyamount: 5currency: #USD.m2 := Moneyamount: 7currency: #GBP.m1 + (m2 + m1) 5 USD + 7 GBP + 5 USDTo complete the Double Dispatch, we have to implement addMoneySum: in Money andMoneySum. The implementation in Money is simple, we just turn around and send addMoney: tothe MoneySum, trusting the existing implementation to work:Money>> addMoneySum: aMoneySum^aMoneySum addMoney: selfWe can test this:<strong>Coding</strong> <strong>Patterns</strong> page 145 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!