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 pattern 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.

If you have git installed, then you can directly clone the design-patterns repository. I have kept code for all design patterns at Each branch is a different design pattern.

Go to your working directory and then follow below steps:

  1. git clone
  2. cd design-patterns
  3. git checkout visitor

If you don’t have git installed, you can either directly download zip or copy paste from below.

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.


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 *