Visitor - Double Dispatch

Description

The Double Dispatch pattern is a generalization of most Visitor patterns. It lets the dispatcher request different operations on each class of element without modifying the existing classes.

Profile

UML profile of design pattern

Profile download (Rational Rose model)

OCL Constraints

context Dispatcher
inv: not self.isAbstract

context Element
inv: self.treeTop implies (self.isAbstract and self.dEE->size() = 1)

inv: self.isAbstract implies (self.specialization->size() > 0 and
self.specialization->forAll (c | c.child.oclIsKindOf (Element)))

inv: not self.treeTop implies (self.dEE->size() = 0)

context AcceptOp
inv: self.parameter->exists (p | p.kind <> ParameterDirectionKind::out
and p.kind <> ParameterDirectionKind::return and p.type.oclIsKindOf(Element)
and p.type.oclAsType(Element).treeTop)

context VisitOp
inv: self.parameter->exists (p | p.kind <> ParameterDirectionKind::out and
p.kind <> ParameterDirectionKind::return and p.type.oclIsKindOf (Dispatcher))

context aDispatcherElement
inv: self.dEE.isNavigable and self.dED.isNavigable
	

Explanation of Profile

  1. There is a hierarchy of element classes with an abstract base class and one or more sub-classes.
  2. The base element class has at least one operation to visit a concrete element that has a dispatcher as a parameter.
  3. There is a concrete dispatcher class that has a bidirectional association with the base element class.
  4. The dispatcher class has at least one operation to accept a base element object which would in turn call the visit operation for the object.

Correct Instance

correct design pattern instance

Incorrect Instance

incorrect design pattern instance

The association should be between MazeElement and MazeVisitor. Then again, in the DD pattern there should be no Dispatcher class hierarchy, so the abstract MazeElement class should not be present and its accept() operation should be moved down into the Door class.

Tool Output

output of tool