Design Patterns - SPLessons
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. [java]public interface Sports { public void accept(SportsName sportsName); }[/java] Creating a class Cricket which implements Sports. [java] public class Cricket implements Sports { public void accept(SportsName sportsName)//overrides the interface method { sportsName.visit(this); } } [/java] Creating a class Football which implements Sports. [java] public class Football implements Sports { public void accept(SportsName sportsName)//overrides the interface method { sportsName.visit(this); } } [/java] Computer class implements Sports [java] 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); } }[/java] Creating iinterface SportsPartVisitor. [java] public interface SportsPartVisitor { public void visit(Computer computer); public void visit(Cricket cricket); public void visit(Football football); }[/java] SportspartDisplayVisitor class implements SportsPartVisitor. [java] 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."); } }[/java] VisitorPattern class defines the useage of visitorpattern. [java] public class VisitorPattern { public static void main(String[] args) { SportsPart computer = new Sports();//creates object for SportsPart class computer.accept(new SportsPartDisplayVisitor()); } }[/java]

shape Output

The result will be as follows. [java] Displaying Computer. Displaying Cricket. Displaying Football. [/java]

Summary

shape Key Points

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