visitor pattern is used to add extra operations for group of class with out change their structures
interface Operation{
void op(){};
}
class AddOperation implements Operation{
void op(){
System.out.println("add operation");
}
}
class minusOperation implements Operation{
void op(){
System.out.println("minus");
}
}
//this can be used to get rid of the if or select case statements
public class Test{
public static void main(String args[]){
Operation o = new AddOperation();
o.op();
}
}
//here comes visitor pattern
interface Visitor(){
void visit(Operation o);
}
class ToAdd implements Visitor{
void visit(Operation o){
o.op();
}
}
class ToSubstract implements Visitor{
void visit(Operation o){
o.op();
}
}
public class MyTest{
public static void main(String[] args){
Operation op = new MinusOperation();
Visitor v = new ToSubstract();
v.visitor(op);
}
}
best example is Pizzas and delivery methods,for Pizza,we need to order it,all Pizza has this method,Delivery interface has a visit method that will pass Pizza and call Pizza's order method,so we add operations(different delivery method) to group of class( different Pizzas),we do not need to change Pizzas structure,becaus it is extracted to interface.
No comments:
Post a Comment