To support
(DiceHandle new add: (Dice faces: 4); yourself)
+ (DiceHandle new add: (Dice faces: 6); yourself)
We defined + as
DiceHandle >> + aDiceHandle
| handle |
handle := DiceHandle new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handleBetween
DiceHandle >> + aDiceHandle
| handle |
handle := DiceHandle new.And
DiceHandle >> + aDiceHandle
| handle |
handle := self class new.Let us see....
DiceHandle subclass: MemoDiceHandle
....(MemoDiceHandle new add: (Dice faces: 4); yourself)
+ (MemoDiceHandle new add: (Dice faces: 6); yourself)
> aDiceHandle
We get a DiceHandle instance back and not a MemoDiceHandle instance!!!
DiceHandle >> + aDiceHandle
| handle |
handle := self handleClass new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handleDiceHandle >> handleClass
^ DiceHandle
A subclass may redefine handleClass
MemoDiceHandle >> handleClass
^ MemoDiceHandle(MemoDiceHandle new add: (Dice faces: 4); yourself)
+ (MemoDiceHandle new add: (Dice faces: 6); yourself)
> aMemoDiceHandleWe get an instance of the subclass!
Let us see
handleClassDiceHandle >> + aDiceHandle
| handle |
handle := self class new.
self dice do: [ :each | handle addDice: each ].
aDiceHandle dice do: [ :each | handle addDice: each ].
^ handleself class always returns the class of the receiver
If we define a subclass of DiceHandle,
and send the message + to an instance
DiceHandle new, + does not return an instance of the subclass but of DiceHandleself class new, + returns an instance of the receiver: an instance of a potential subclass/