Visitor design pattern is used to perform operation on elements of an object structure.
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.
The intent is to represent the operation of element of object structure by visitor.
Problem
An object structure contains many objects. There is a need to perform different operations on these objects. Doing
these operations in their classes will add complexity.
Adding different and unrelated operation in class will lead to confusion and will make it complex.
Solution
Have a separate object for operations of an element of object structure. Call the appropriate concrete object
operation of that element when you traverse the elements.
So there will be visit operation for each element of object structure in separate class. While visiting the element the
appropriate operation will be performed.
Where it is applicable?
An object structure has multiple objects and need to visit and apply the operations on it.
Structure
Participant classes
Visitor class provides interface for visit operation for each element of object structure.
Concrete classes ConcreteVisitor1 and ConcreteVisitor2 implement the methods for the interface provided
by abstract class Visitor. These methods have element instance as parameter.
Element class is part of ObjectStructure. It has method Accept() which gets Visitor instance as parameter.
The concrete class ConcreteElement class implements the method Accept() which in turn calls the appropriate
Visitor method.
ObjectStructure may contain multiple elements. Visitor visits the elements of ObjectStructure.
How they work together?
The client creates the concrete visitor. While traversing the element of object structure it calls the element
Accept() method with visitor as parameter. Inside Accept() method it uses visitor to call visit operation for that element
with element as parameter. Inside the visit element operation it does the appropriate work applicable for that operation.
So here the operation is performed on elements of ObjectStructure. This provides flexibility to add new operation by
adding a new visitor. It is assumed that object class structure will not be changed much. Adding a new element is
complicated and will require adding of new abstract operation in visitor class and its implementation in concrete classes.
So it is good to use visitor pattern when object structure is stable and addition or modification is required on
operations.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on Design Patterns.