Visitor Design Pattern

A Behavioral Design pattern

Amrit Lal Sahu
2 min readOct 25, 2019
Photo by shutterstock

Visitor design pattern is a way of separating an operational logic or algorithm from an object structure on which it operates.

Visitor lets you define new operations to existing object structures without modifying the structures.

It provides good use of the Open/Closed principle as we won’t modify the code, but we’ll still be able to extend the functionality by providing a new Visitor implementation.

When to use the Visitor Design Pattern:

  • Use the Visitor when you need to perform distinct and unrelated operation on all elements of a complex object structure.
  • The classes defining the object structure rarely change, however you often want to define the new operation over the structure. Therefore, new operation can be added to the visitor hierarchy by not polluting the existing design.
  • Element object has to accept the visitor object so that visitor object handles the operation on the element object.

Design components

Programs :

Advantages :

  • If the logic of operation changes, then we need to make changes only in the visitor implementation rather than doing it in all the item classes.
  • Adding a new item to the system is easy, it will require change only in visitor interface and implementation and existing item classes will not be affected.
  • Gather related operations into a single class rather than force you to change or derive classes to add these operations

Disadvantages :

  • We should know the return type of visit() methods at the time of designing otherwise we will have to change the interface and all of its implementations.
  • If there are too many implementations of visitor interface, it makes it hard to extend.
  • Visitor is not good for the situation where “visited” classes are not stable. Every time a new Composite hierarchy derived class is added, every Visitor derived class must be amended.

Relations with Other Patterns:

  • Visitor is a powerful version of the Command pattern. Its objects can execute operations over various objects of different classes.
  • Visitor can be used to execute an operation over an entire Composite tree.
  • Visitor can be used along with Iterator to traverse a complex data structure and execute some operation over its elements, even if they all have different classes.

Thanks for reading this article. Please Clap, Follow and comments to motivate me for posting more articles in the days to come.

Reference :

https://en.wikipedia.org/wiki/Visitor_pattern

--

--