Design Patterns

Visitor



Design Pattern Type: Behavioral

GoF Statement of Intent:


Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Brief Overview:



This patter provides a way of separating an algorithm from an object structure it operates on. This provides a way of adding new operations to existing structures without modifying those structures. In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves. Instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. While powerful, the visitor pattern is more limited than conventional virtual functions. It is not possible to create visitors for objects without adding a small callback method inside each class.
UML Diagram:

Discussion and In-class Example:

Take another look at the menus for the Pancake House, Café, and Diner. Suppose you wanted to add the capability to get nutritional information on each menu item and even on ingredients in each. You could use the approach illustrated in the image below and add the needed methods. This might work, but you are greatly exposing the inner workings of each item and all of the methods may not be appropriate.

If instead you use the Visitor pattern then each item only has to add one method, getState(). Now you create a Visitor object whose purpose is to gather information on the state objects and return the information. The Visitor uses a Traverser object which knows how to traverse the composite hierarchy.

Advantages of using the Visitor
  1. Allows you to add operations to a composite hierarchy without changing the structure of the hierarchy.
  2. Adding new operations is relatively easy.
  3. The code for operations performed by the Visitor is centralized.

Disadvantages of using the Visitor
  1. The complete encapsulation of the composite structure objects is compromised.
  2. Because of the traversal function, changes to the composite structure are more difficult, but this is only true if you are changing the structure not if you are just adding more objects in the same organization.