Undo a Visitor Pattern

Visitor is a classical object-oriented design pattern. Undoing a visitor – the topic of this page – is to remove all traces of a Visitor pattern.

 

In a Visitor pattern, all methods of a program with the same signature (method name, parameter types in order) are moved into a single class, called a "Visitor". The original methods remain, except their bodies delegate to their corresponding moved method. The ¡°Undo¡± Visitor pattern moves all these methods back to their originating classes. The figure below summarizes the transformation:

 

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

 

 

Below is our "Mechanics Section" that explains how to undo a visitor. The same procedure is used for undoing visitors for other methods.

 

1. The starting program has this class diagram.

 

 

2. For each visit method in DrawVisitor: move it back to its original class. The first parameter of every visit method (e.g., Graphic of visit(Graphic)) indicates the original class. You may assume that only visit methods exist in DrawVisitor.

 

 

3. Each class (Picture, Square, Triangle, and Graphic) has an accept and a visit method with the same arguments and return type. (This is to be expected, as the accept method delegates to the visit method). Replace the body of each accept method with the body of the visit method, and delete the visit method. Equivalently, inline the visit method into the accept method, eliminating the visit method.

 

 

4. Remove the DrawVisitor type parameter from all accept methods (and relatives*).

 

*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 accept() method, you have to rename or alter the arguments in ALL of the accept() methods. We use the term relatives to refer the set of methods that should be updated simultaneously.

 

 

5. Rename all accept relatives to ¡°draw¡±, the original method name.

 

 

6. Delete the visitor class and you¡¯re done!