Advantage of the visitor pattern- Easy to add new opeartions to the datastructure by adding new visitors: (see http://de.wikipedia.org/wiki/Besucher_(Entwurfsmuster))
Disadvantages of the visitor pattern- New classes of datastructure elements (e.g. Body) requires to change all visitors, see also classes marked with * in example
Example:interface Visitor {
void visit(Wheel wheel);
void visit(Engine engine);
* void visit(Body body);
void visit(Car car);
}
class PrintVisitor implements Visitor {
public void visit(Wheel wheel) {
System.out.println("Visiting "+ wheel.getName()
+ " wheel");
}
public void visit(Engine engine) {
System.out.println("Visiting engine");
}
* public void visit(Body body) {
System.out.println("Visiting body");
}
public void visit(Car car) {
System.out.println("Visiting car");
}
}
class DoVisitor implements Visitor {
public void visit(Wheel wheel) {
System.out.println("Steering my wheel");
}
public void visit(Engine engine) {
System.out.println("Starting my engine");
}
* public void visit(Body body) {
System.out.println("Moving my body");
}
public void visit(Car car) {
System.out.println("Vroom!");
}
}
interface Visitable {
void accept(Visitor visitor);
}
class Body implements Visitable{
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Car implements Visitable {
public void accept(Visitor visitor) {
visitor.visit(this);
engine.accept(visitor);
body.accept(visitor);
for(Wheel wheel : wheels) {
wheel.accept(visitor);
}
}
Hole example you find here:
http://en.wikipedia.org/wiki/Visitor_pattern