Double dispatch

L. M. Rappaport rapp at lmr.com
Wed Nov 4 15:02:04 UTC 1998


On Wed, 4 Nov 1998 08:00:27 -0600 (CST), you wrote (with possible
editing):

>Gang,
>
>I've seen quite a few references to double dispatching. What is that?
>URL's, pointers to docs, or a simple RTFM (but *which* FM) would be
>appreciated.
>
>Jim

I'm new to Squeak, so my notation might be wrong, but here's an
example based on the other Smalltalks I'm familiar with:

	Say you have a document class.  You want the document to appear in
different colors based on some criteria, like urgency.  I.e., you want
the behavior of the document object to change throughout it's life.  A
good example of the State pattern.

	One way to do it is via double dispatching.  The Document class
will have a method called foregroundColor, but instead of it doing
anything directly, you decide to have Document delegate it's
foregroundColor to one of its Documents instance variables - theColor
which will contain a simple object which returns color.  

	This color object will be part of a simple polymorphic family of
classes, such as UrgentColor and NormalColor.

	UrgentColor has a method;  

	UrgentColor>>foregroundColor
		^Color red

	NormalColor has the same method but with different behavior:

	NormalColor>>foregroundColor
		^Color black

	Now you add accessor methods to Document:

	Document>>color: aColor
	
		theColor := aColor

	Document>>color

		^theColor

	and:

	Document>>urgent
		
		self color: UrgentColor new 

	Document>>normal
	
		self color: NormalColor new
		
	To use this, you give Document a foregroundColor method as
follows:

	Document>>foregroundColor

		self theColor foregroundColor

What is happening here is:

	You send the message "foregroundColor" to a Document object
	It resends the message "foregroundColor" to the delegated object
which lives in Document's instance variable.

This is double dispatch - when you call Documents foreground color, it
instead goes to its instance variable and dispatches the method there.
Now granted this is a lot of trouble to go to just to avoid an ifTrue:
[] ifFalse: [] construct, but you can see where it might be both
useful and powerful when several or many methods change behavior based
on state.  (In fact this is a design pattern called the State pattern)
I.e., double dispatch works really slick when you want to delegate
behavior in one object to another. It is good for "policy" objects.

Hope this clears it up.  OTOH, if I'm full of crap, I'm sure someone
will mention it!

Regards,

Larry
--
rapp at lmr.com
 





More information about the Squeak-dev mailing list