Double Dispatch Pattern


Problem


Sometimes the computational path in a program needs to differ based on the runtime arguments it was called with.

Solution


The Double Dispatch pattern prescribes a mechanism to call different concrete functions depending on the types of objects involved in the call.

Related Patterns


  • Visitor

Discussion


Double Dispatch is prominently used in the Visitor pattern, where different operations on an object produce different results based on the type of the calling object.

Examples


The Visitor pattern usees an implementation of Double Dispatch.

Code


Foo and bar are C++ classes. If bar::foobar() is called, the overloaded method will be selected based on the type of the argument selected by the method signature.

class foo{
public:
  virtual void foobar(foo& f);
}
class bar{
  void foobar(foo& f){
    cout << "Foo" << endl;
  }
  void foobar(int& i){
    cout << "I am an int" << endl;
  }
public:
  void getType(foo& f){
    f.foobar(*this);
  }
}