Design Patterns - Visitor

design-patterns

Design Patterns - Behavioral - Visitor.

In Visitor pattern, we use a visitor class which changes the executing algorithm 
of an element class. By this way, execution algorithm of element can vary as and 
when visitor varies. This pattern comes under behavior pattern category. As per 
the pattern, element object has to accept the visitor object so that visitor 
object handles the operation on the element object. 

We are going to create a ComputerPart interface defining accept opearation.  
Keyboard, Mouse, Monitor and Computer are concrete classes implementing 
ComputerPart interface. We will define another interface ComputerPartVisitor 
which will define a visitor class operations. Computer uses concrete visitor to 
do corresponding action.

// Step 1: Define an interface to represent element.
public interface ComputerPart {
   public void accept(ComputerPartVisitor computerPartVisitor);
}

// Step 2: Create concrete classes extending the above class.
public class Keyboard implements ComputerPart {
   public void accept(ComputerPartVisitor computerPartVisitor) {
      computerPartVisitor.visit(this);
   }
}

public class Monitor implements ComputerPart {
   public void accept(ComputerPartVisitor computerPartVisitor) {
      computerPartVisitor.visit(this);
   }
}

public class Mouse implements ComputerPart {
   public void accept(ComputerPartVisitor computerPartVisitor) {
      computerPartVisitor.visit(this);
   }
}

public class Computer implements ComputerPart {
   ComputerPart[] parts;

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

   public void accept(ComputerPartVisitor computerPartVisitor) {
      for (int i = 0; i < parts.length; i++) {
         parts[i].accept(computerPartVisitor);
      }
      computerPartVisitor.visit(this);
   }
}

// Step 3: Define an interface to represent visitor.
public interface ComputerPartVisitor {
    public void visit(Computer computer);
    public void visit(Mouse mouse);
    public void visit(Keyboard keyboard);
    public void visit(Monitor monitor);
}

// Step 4: Create concrete visitor implementing the above class.
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
   public void visit(Computer computer) {
      System.out.println("Displaying Computer.");
   }

   public void visit(Mouse mouse) {
      System.out.println("Displaying Mouse.");
   }
   public void visit(Keyboard keyboard) {
      System.out.println("Displaying Keyboard.");
   }

   public void visit(Monitor monitor) {
      System.out.println("Displaying Monitor.");
   }
}

// Step 5: Use the ComputerPartDisplayVisitor to display parts of Computer.
ComputerPart computer = new Computer();
computer.accept(new ComputerPartDisplayVisitor());
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License