Visitor Pattern

This lesson discusses the visitor pattern which adds new behavior to composites without modifying the composite's or it's underlying elements' classes.

What is it ?

The visitor pattern allows us to define an operation for a class or a class hierarchy without changing the classes of the elements on which the operation is performed.

Recall the Airforce class example from the Composite Pattern lesson. The Airforce class is a composite consisting of several different kinds of airplanes. It can be thought of as the object structure on whose elements we want to conduct operations. The elements would be the individual planes that make up the airforce object structure.

Say if we are tasked with monitoring of various metrics for each aircraft such as remaining fuel, altitude and temperature then one option would be to build this functionality inside the abstract class of all the airplanes. The consequence would be that we'll need to implement the new methods in all the airplane subclasses. Now imagine, a few days later we are tasked with calculating the total price tag for the Airforce. We will now add another method to the abstract airplane class or interface that'll return the price for each individual plane and sum it across all the airplanes.

There are several problems in our scenario, first the airplane class shouldn't be responsible for monitoring or pricing data. It should just represent the aircraft. With each additional functionality, we'll end up bloating our aircraft classes with new unrelated methods. The visitor patterns lets us out of this dilemma by suggesting to have a separate class that defines the new functionality related to the aircraft. The methods in the AircraftVisitor class would take the aircraft object as an argument and work on it. This saves us from changing our aircraft classes each time we need to support a new functionality relating to the Airforce class.

Formally, the pattern is defined as defining operations to be performed on elements of an object structure without changing the classes of the elements it works on.

The pattern is suitable in scenarios, where the object structure class or the classes that make up its elements don't change often but new operations over the object structure are desired.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy