Visitor Design Pattern

The Visitor Design Pattern is part of Behavioural Design Patterns in object-oriented programming and is invoked when there are several similar objects in hand on which a certain operation is to be performed. As this pattern is responsible for maintaining communication between two or more objects, it makes sure there is as less coupling as possible thereby keeping the code simple and reusable. A visitor class acts or implements on visitable classes by governing the principles under which the individual objects will work.

Definition

As defined in the Gang of Four: ‘The visitor pattern presents an operation to be performed on elements of an object structure’. In simpler words, a visitor class allows users to add functionalities to the element classes without altering any existing code. The visitor class takes out the implementation logic from objects and makes a separate class by itself.

Structure

The main framework of a visitor pattern follows the visitor and visitable classes.

  • The visit class has a visit() method that looks into element classes and similar objects.
  • The visitable class has an accept() method that allows the visit class to implement functionalities into its scope.

Example and Code

We wil device a simple shopping cart system where the contents of the cart wil be treated as elements. The visitor will act as the cashier who will check for prices and weights of the items when your are checking out from the system.

public interface Elements{
public void accept(Visitor vis);
}

// The class below will be concrete element item. Let us choose a cartoon of eggs

public class Eggs implements Elements{
private double mrp;
private double wgt;

public void accept (Visitor vis){
vis.visit(this);
}

public double getMRP() {
return mrp; }

public double getWeight(){
return wgt;
}
}

//Let us create the cashier interface that will be the visitor in this case

public iinterface Visitor{
public void visit (Eggs eggs);
…. //Other items on your shopping cart
}

//Finally we will make the checking out counter where the cashier sits

public class CashierCheckOut implements Visitor {
private double totalCost;
private double totalWeight;
public void  visit(Eggs eggs) {
totalCost+= eggs.getMRP();
totalWeight+=eggs.getWeight();
.
.
. //For other items, the same process is repeated.

public double total() {
return totalCost;
}
}

 

When to use the Visitor Design Pattern

As this pattern helps keep your code decoupled at all times, you can use it when you need to perform several functions (mostly unrelated to one another) on a wide range of similar behaving objects. This pattern can also be used when the objects have varying interfaces.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.