Double Dispatch

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m (*1 Typo Fixed)
m (Adding a link to an example)
 
Line 18: Line 18:
  
 
In some situations it is not so desirable to have such a general association being allowed. In situations such as this the method calls can be restricted by not referring to the [[abstract class]] as method arguments but using concrete types instead as in the above example.
 
In some situations it is not so desirable to have such a general association being allowed. In situations such as this the method calls can be restricted by not referring to the [[abstract class]] as method arguments but using concrete types instead as in the above example.
 +
 +
==Example==
 +
Here is a more elaborate discussion on [http://www.lostechies.com/blogs/derekgreer/archive/2010/04/18/double-dispatch-is-a-code-smell.aspx Double Dispatch] with example.
  
 
==See also==
 
==See also==
 
* [[State machine design]]
 
* [[State machine design]]
 
* [[Visitor]]
 
* [[Visitor]]

Latest revision as of 14:22, 25 July 2010

Double dispach

Double dispatch is a useful method for creating a bidirectional association between two objects without creating a tight coupling between them. When an object needs to create the connection whether permanent for the life of the object or temporary for just one transaction, one object passes itself as an argument to the other. The second object can then pass itself back into the first object for the link to be complete. This is used in the visitor pattern.

Initially a controller object will call the accept method on an object of type ClassA using an object of type ClassB as an argument.

objectA.accept(objectB);

Then the object of type ClassA calls back to objectB passing itself as an argument.

b.performFunction(this);

In this way the types of the classes are not so important and if any one subclass in the hierarchy needs different actions performed this can be achieved by method overloading for that subclass.

For example adding to ClassB1:

public void performFunction(ClassA2 a){
               /* Do something different here */
}

Will create a different behaviour when a ClassA2 is used.

In some situations it is not so desirable to have such a general association being allowed. In situations such as this the method calls can be restricted by not referring to the abstract class as method arguments but using concrete types instead as in the above example.

Example

Here is a more elaborate discussion on Double Dispatch with example.

See also

Personal tools