Visitor Design Pattern Implementation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In this article we are going to understand yet another design pattern i.e. visitor design pattern implementation.

Visitor Design Pattern Implementation:

Gang of Four defines visitor patter as,

Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Class Diagram:

Visitor Class Diagram

Visitor Class Diagram

Components Involved in visitor pattern:

  • Visitor: An interface declaring methods for all types of Visitable classes.
  • ConcreteVisitor1 and ConcreteVisitor2 both implement Visitor interface and implement all methods.
  • Visitable: Actual visitable elements which define accept(), operation. visitor.visit() is called from here.
  • VisitableA and VisitableB are concrete implementations for Visitable.
  • ObjectStructure: This also implements Visitable and HAS-A collection of Visitable elements

Visitor Design Pattern Implementation:

Consider a scenario where we have a Bike and Engine and FuelTank are parts of Bike. We have two types of visitors, i.e. PartsChecker which checks whether all bike parts are working fine, and PartsOperator which operates all bike parts. We will write visitor design pattern implementation as below.

  • Bike, Engine and FuelTank implement Visitable, and implement accept(Visitor visitor); 
  • PartsChecker and PartsOperator implement visit() methods.

Visitor.java:

PartsChecker.java:

PartsOperator.java:

FuelTank.java:

Engine.java:

Now we will create Bike class which will also hold reference to bike parts.

Let us test our visitor design pattern implementation using Rider class.

Output:

Visitor Design Pattern Implementation Diagram:

Visitor Design Pattern Implementation

Visitor Design Pattern Implementation

 

I hope this article helped understand visitor design pattern implementation.

Share Button

Leave a Reply

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