Design Patterns - SPLessons

Visitor Pattern

Chapter 28

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Visitor Pattern

Visitor Pattern

shape Description

Visitor Pattern is a Behavioral Pattern used to perform the operations on a group of similar objects. Using Visitor pattern, algorithm can be separated from the object structure.Visitor is an external class and can access the data of another class. Additional features can be added to a class without changing the class. 

shape Advantages

  • More operations can be performed on objects using Visitor Pattern.
  • Logical operation of the class can be moved using Visitor Pattern.

shape Conceptual
figure

shape Examples

Creating an interface Sports.

public interface Sports
 {
public void accept(SportsName sportsName);
}

Creating a class Cricket which implements Sports.

public class Cricket implements Sports
 {
   public void accept(SportsName sportsName)//overrides the interface method 
{
      sportsName.visit(this);
   }
}

Creating a class Football which implements Sports.

public class Football implements Sports 
{
   public void accept(SportsName sportsName)//overrides the interface method
 {
      sportsName.visit(this);
   }
}

Computer class implements Sports

public class Computer implements Sports 
{	
   Sports[] sports;

   public Computer()
{
      sports = new Sports[] {new Cricket(), new Football()};		
   } 
   public void accept(SportsName  sportsName) //overrides the interface method
{
      for (int i = 0; i < parts.length; i++) 
{
         parts[i].accept(sportsName);
      }
      sportsName.visit(this);
   }
}

Creating iinterface SportsPartVisitor.

public interface SportsPartVisitor
 {
	public void visit(Computer computer);
	public void visit(Cricket cricket);
	public void visit(Football football);
	
}

SportspartDisplayVisitor class implements SportsPartVisitor.

public class SportspartDisplayVisitor implements SportsPartVisitor 
{
   public void visit(Computer computer)//overrides the interface method
      System.out.println("Displaying Computer.");
   }  
   public void visit(Cricket cricket)//overrides the interface method 
{
      System.out.println("Displaying Cricket .");
   }   
   public void visit(Football football)//overrides the interface method
 {
      System.out.println("Displaying Football.");
   }

 }

VisitorPattern class defines the useage of visitorpattern.

public class VisitorPattern 
{
   public static void main(String[] args)
 {
      SportsPart computer = new Sports();//creates object for SportsPart class
      computer.accept(new SportsPartDisplayVisitor());
   }
}

shape Output

The result will be as follows.

Displaying Computer.
Displaying Cricket.
Displaying Football.

Summary

shape Key Points

  • Adding new features to a system is easy.
  • Loose coupling of objects can be done easily in visitor pattern.