Double Dispatch

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
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.
 +
 +
==See also==
 +
* [[State machine design]]

Revision as of 09:02, 3 October 2008

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 in used in the visitor pattern.

Initially a controller object will call the accept method on an obect of type ClassA usint 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.

See also

Personal tools