Visitor Design Pattern in Java
Visitor lets you add a new operation to many classes without changing those classes. The operation lives in a separate visitor class.
Real life example
A tax officer visits different businesses (shop, factory) and calculates tax in a different way for each.
When to use
You have a stable set of classes but you keep adding new operations on them.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Square() };
for (Shape sh : shapes) sh.accept(new AreaVisitor());
}
}
interface Shape { void accept(Visitor v); }
class Circle implements Shape { double r = 2; public void accept(Visitor v) { v.visit(this); } }
class Square implements Shape { double s = 3; public void accept(Visitor v) { v.visit(this); } }
interface Visitor {
void visit(Circle c);
void visit(Square s);
}
class AreaVisitor implements Visitor { // new operation, shapes are untouched
public void visit(Circle c) { System.out.println("Circle area: " + Math.PI * c.r * c.r); }
public void visit(Square s) { System.out.println("Square area: " + s.s * s.s); }
}Output
Circle area: 12.566370614359172
Square area: 9.0