Make a Visitor pattern

Visitor is a classical object-oriented design pattern. The basic idea is to move all methods (typically within the same class hierarchy) with the same signature (method name, parameter types in order) into a single class, called a "Visitor". The figure below summarizes the transformation where all draw() methods in the Graphic hierarchy are moved into visitor "DrawVisitor"; Graphic.draw() method becomes DrawVisitor.visit(Graphic), Picture.draw() becomes DrawVisitor.visit(Picture), etc.

 

Please reference a simple tutorial about UML Class Diagram if you¡¯re not familiar with it.

 

 

Below is our "Mechanics Section" that shows how the class diagram changes in each step when we make a Visitor pattern for draw() methods. The same procedure is used for creating visitors for other methods.

 

1. Starting program has this class diagram.

 


2. Create a visitor class.

 

 

3. Make the visitor class a Singleton.

 

 

4.  Add a DrawVisitor type parameter to all draw() methods (and relatives*). The default value of the parameter is ¡±DrawVisitor.singleton¡±.

 

*Relatives mean all methods that have the same signature (name and parameter types in order) in the same class/interface hierarchy. If you rename or alter the arguments to any draw() method, you have to rename or alter the arguments in ALL of the draw() methods. We use the term relatives to refer the set of methods that should be updated simultaneously.

 

 

5. Move draw() relatives to the visitor class and leave delegates behind.

 

*Relatives may include methods that cannot be moved. For example, it is not possible to move interface methods or abstract methods (which do not exist in this example).

 

 

6. Rename all draw() methods in the visitor class to ¡°visit¡±. Rename delegate relatives to ¡°accept¡±. You¡¯re done!