Design Pattern Basic Tutorial

adplus-dvertising
Visitor Pattern
Previous Home Next

It is used to define the new operation to deal with the element classes without changing the structure of the class.

Benefit and use of Visitor Pattern
  1. With help of this we can Add operations on a bunch of classes which have different interfaces.
  2. Traverse the object structure to gather related operations
  3. The Visitor pattern provide the facility to Easily add new operations.
  4. Crossing class hierarchies may break encapsulation.

We can write the code Without using template method pattern, but when you write without template then you may write more lines of code. With the use of the design pattern we don't have any side effect and we don't need to cast in or out.

Example

package r4r;
import java.util.*;
interface Visitor {
public void visit(sandwich s);
}
interface sandwich {
public String order();
}
class john implements sandwich {
final String name = "John";
public String order() {
return name;
}
	
}
class sandwichshop implements sandwich {
final String name = "sandwichshop";
public String orders() {
return name;
}
@Override
public String order() {
// TODO Auto-generated method stub
return null;
}
}
class Father implements sandwich {
final String name = "Father";
public String order() {
return name;
}
}
class Pickup implements Visitor {
private String name;
private final String method = "pick up";
public void visit(sandwich s) {
name = s.order();
}
    
public String toString() {
return name + " " + method;
}
}
class Eat implements Visitor {
private String name;
private final String method = "eat";
    
public void visit(sandwich s) {
name = s.order();
}
    
public String toString() {
return name + " " + method;
}
}
class Delivery implements Visitor {
private String name;
private final String method = "delivery";
    
public void visit(sandwich s) {
name = s.order();
}
    
public String toString() {
return name + " " + method;
}
}
class breakfast {
public sandwich getbreakfast() {
switch ((int)(Math.random()*3)){
case 0: return new john(); 
case 1: return new sandwichshop(); 
case 2: return new Father(); 
default: return null;
}
}
public Visitor hows() {
switch ((int)(Math.random()*3)){
case 0: return new Pickup(); 
case 1: return new Eat(); 
case 2: return new Delivery(); 
default: return null;
}
}    
}
public class visittest {
public static void main(String[] args) {
List sandwichlist = new ArrayList();
sandwichlist.add(new john());
sandwichlist.add(new sandwichshop());
sandwichlist.add(new Father());
Iterator it = sandwichlist.iterator();
System.out.println("How many sandwich restaurants in this area?");
while (it.hasNext()) {
System.out.println(((sandwich)it.next()).order());
}
breakfast bf = new breakfast();
sandwich sw = bf.getbreakfast();
Visitor v = bf.hows();
v.visit(sw);
System.out.println("\nWhich store for break fast?");
System.out.println(v);
}
}
Previous Home Next