Java Behavioral Design Patterns – Visitor Design Pattern

In this article, we will go through another pattern from behavioral category: Visitor Design Pattern.

The visitor design pattern is generally used when you have to do an operation on heterogeneous objects. The operation being performed is kept in different class and the objects of classes that need to be operated upon are passed to this method. This pattern can be used when you see:

  • An object structure requires many unrelated operations
  • There is the least possibility of change in any of the classes in the object structure.
  • You need to work across several independent class hierarchies.
  • New operations need to be added frequently.

Visitor Design Pattern by Example

To understand the pattern we will consider a real-world problem of Taxi Transport. In this, a taxi can transport persons, animals, and luggage. Based on type its fare may vary. We will apply Visitor Pattern to calculate total fare of the taxi.

Let us define a Transportable interface that will be implemented by each of the types that can be transported in a taxi.

Now we will define Visitor interface

Note our Visitor interface has visit method for each of the type it is going to process.

The different types are implemented as

Person

Animal

Luggage

The concrete class which implements the Visitor interface does all the processing on each of the types

Running the Example

See how our demo is iterating through all the transportable items and executing accept method.

Output

Advantages

  • Visitor pattern allows a new operation to be defined without any changes in the implementation of the class.
  • If the logic of operation changes, then we need to make a change only in the visitor implementation, not in all the item classes.

Disadvantages

  • If a new type is added, then a visitor interface and concrete class need to be modified.
  • The superclass Visitor has to be aware of all types of nodes.

Conclusion

In this article, we understood Visitor Design Patter with the help of a simple example. The source code is available in our Github repository.

Download Code

Add a Comment

Your email address will not be published. Required fields are marked *