Behavioral Design Pattern

Visitor Design Pattern in Java

Add operations to an object structure without modifying the element classes.

In this lesson: Visitor separates an operation from the object structure on which it works. New operations can be added through visitor implementations.

Overview

Visitor is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.

Implementation

interface Shape { void accept(ShapeVisitor visitor); }
final class Circle implements Shape { public void accept(ShapeVisitor visitor) { visitor.visit(this); } }
interface ShapeVisitor { void visit(Circle circle); }
final class AreaVisitor implements ShapeVisitor { public void visit(Circle circle) { System.out.println("Calculate area"); } }
new Circle().accept(new AreaVisitor());

When should you use it?

Use Visitor when an object structure is stable but many unrelated operations must be added. It can be harder to maintain when the element hierarchy changes frequently.

Next step: Continue with the Design Patterns course and explore the next pattern.