Visitor Pattern

Visitor is a behavioral pattern that uses a visitor class which changes the executing algorithm of an element class. By this way, execution algorithm of element can vary as and when a visitor varies. Element object has to accept the visitor object so that object handles the operation on the element object.

In the following example there is a ComputerPart interface defining accept operation along with concrete classes implementing ComputerPart : Keyboard, Mouse, Monitor, Computer. Another interface, ComputerPartVisitor, defines a visitor class operations. Computer uses concrete visitor to do corresponding action. VisitorPatternDemo will use Computer and ComputerPartVisitor classes to demonstrate use of visitor pattern.

Visitor Pattern UML Diagram

Step 1 : Define an interface to represent element

public interface ComputerPart {
default void accept(ComputerPartVisitor computerPartVisitor, ComputerPart computerPart) {

Step 2 : Create concrete classes implementing the above interface

public class Keyboard implements ComputerPart {}
public class Monitor implements ComputerPart {}
public class Mouse implements ComputerPart {}
public class Computer implements ComputerPart {
ComputerPart [] parts;

public Computer() {
parts = new ComputerPart[] {
new Keyboard(),
new Mouse(),
new Monitor()

public void accept(ComputerPartVisitor computerPartVisitor, ComputerPart computerPart) {
for (int i = 0; i < parts.length; i++) {
parts[i].accept(computerPartVisitor, parts[i]);

Step 3 : Define an interface to represent visitor

public interface ComputerPartVisitor {
void visit(ComputerPart computerPart);

Step 4 : Create concrete visitor implementing the above interface

public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
public void visit(ComputerPart computerPart) {
if (computerPart instanceof Computer) {
System.out.println("Displaying Computer.");
} else if (computerPart instanceof Keyboard) {
System.out.println("Displaying Keyboard.");
} else if (computerPart instanceof Mouse) {
System.out.println("Displaying Mouse.");
} else if (computerPart instanceof Monitor) {
System.out.println("Displaying Monitor.");

Step 5 : Use ComputerPartDisplayVisitor to display parts of Computer

public class VisitorPatternDemo {
public static void main(String[] args) {
ComputerPart computer = new Computer();
computer.accept(new ComputerPartDisplayVisitor(), computer);

The output will be :

Displaying Keyboard.
Displaying Mouse.
Displaying Monitor.
Displaying Computer.

Leave a Reply

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