Visitor Design Pattern in Java
Add operations to an object structure without changing the element classes.
What is Visitor?
Elements accept a visitor, and the visitor contains the operation for each element type. This is useful when the structure is stable but operations change often.
Beginner-friendly Java example
Focus on the roles in the example first. The pattern becomes easier when you can identify the sender, receiver, context, state, or strategy involved.
interface Shape {
void accept(ShapeVisitor visitor);
}
interface ShapeVisitor {
void visit(Circle circle);
void visit(Rectangle rectangle);
}
class AreaVisitor implements ShapeVisitor {
public void visit(Circle circle) {
System.out.println("Circle area");
}
public void visit(Rectangle rectangle) {
System.out.println("Rectangle area");
}
}Benefits and trade-offs
Benefits
- Keeps responsibilities focused.
- Reduces conditional and tightly coupled code.
- Makes behavior easier to extend and test.
Trade-offs
- Can introduce extra objects and interfaces.
- Too many small classes can make simple logic harder to follow.
Real-time use cases
- Compiler operations over syntax trees
- Exporting documents
- Calculating reports
- Applying operations to file structures
Key takeawayAdd operations to an object structure without changing the element classes. Use it when behavior or communication is changing faster than the objects themselves.
