Today, I am here to discuss another behavioral design pattern called Visitor Design Pattern. The Visitor design pattern lets us separate algorithms from the objects on which they operate.

Visitor Design Pattern

  • The Visitor Design Pattern provides a way of separating an algorithm from an object structure on which it operates.
  • A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. It is one way to follow the open/closed principle.
  • The Visitor Design Pattern is used when we like to perform an operation on a group/family of objects.
  • The Visitor Design Pattern is one of the twenty-three well-known GoF design patterns which helps us to move the operational logic from the objects to another class.
  • The **Visitor **allows adding new virtual functions to a family of classes, without modifying the classes.
  • Instead, a **visitor **class is created that implements all of the appropriate specializations of the virtual function.
  • The Visitor Design Pattern makes it possible to define a new operation for (some) classes of an object structure without changing the classes.
  • When new operations are needed frequently and the object structure consists of many unrelated classes, it’s inflexible to add new sub-classes each time a new operation is required.
  • The Element _accepts _the visitor and delegates the operation to the accepted **Visitor **object.
  • The **Visitor **object performs the operation on the element (“visits the element”).
  • The Visitor Design Pattern makes it possible to create new operations independently from the classes of an object structure by adding new visitor objects.

visitor design pattern UML diagram

To understand this, let’s take an example of a Shop, which sells books, fruits, vegetables, and electronics.

#java #tutorial #design pattern #visitor design pattern

Visitor Design Pattern In Java
3.05 GEEK