Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Exploring the Visitor Design Pattern in Java

Java’s Visitor pattern separates operations from element classes. See how accept() enables double dispatch, what it costs when types change, and when to use it.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Java’s Visitor pattern puts operations in separate visitor classes and uses each element’s accept method to route the call to a method for that element’s concrete type. It is a good fit when the set of element types is relatively stable and you expect to add operations; it is less attractive when the hierarchy changes frequently.

What the Visitor pattern does

Visitor represents an operation over objects in a structure while keeping that operation outside the objects’ classes. Instead of adding export, validation, or reporting behavior to every element, you implement each operation as a visitor. The elements provide a way for visitors to identify and handle their concrete types.

As an Amazon Associate I earn from qualifying purchases.

This design shifts where change is easiest: adding another operation is usually localized to a new visitor, while adding an element type usually requires updating the visitor interface and its implementations. The pattern’s classic intent is to represent an operation on elements of an object structure without changing the element classes (PMI, Disciplined Agile).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How Java’s accept method enables dispatch

A typical implementation has an element interface, a visitor interface with one method per concrete element, concrete elements that implement accept, and concrete visitors for operations. This illustrative sketch uses a generic result type; choose result and context parameters to suit the operation:

interface Shape {
    <R> R accept(ShapeVisitor<R> visitor);
}

interface ShapeVisitor<R> {
    R visitCircle(Circle circle);
    R visitRectangle(Rectangle rectangle);
}

final class Circle implements Shape {
    @Override
    public <R> R accept(ShapeVisitor<R> visitor) {
        return visitor.visitCircle(this);
    }
}

The critical line is visitor.visitCircle(this). When a caller invokes shape.accept(visitor) through a Shape reference, Java dynamically dispatches accept to the object’s concrete implementation. Inside Circle.accept, this has compile-time type Circle, so the compiler selects visitCircle(Circle).

Why overloading alone is not enough

Java does not select an overloaded method based on an argument’s runtime class. If the caller has a Shape reference and calls visitor.visit(shape), overload resolution uses the compile-time type Shape, even if the object is a Circle. Visitor combines two mechanisms: dynamic dispatch chooses the concrete accept method, and that method’s typed call chooses the matching overloaded visitor method. This is commonly called double dispatch (Refactoring.Guru’s explanation of Visitor and double dispatch).

How a visitor performs an operation

A concrete visitor implements the operation’s behavior for every element type. For example, an export visitor could provide visitCircle and visitRectangle methods that produce the appropriate output for each shape. The object structure can then be traversed and each element can accept that visitor. Refactoring.Guru’s Java example uses shape types such as Dot, Circle, Rectangle, and CompoundShape, with an XMLExportVisitor operation (Visitor in Java).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A visitor’s signature can also include a result and a context parameter. Oracle’s Java SE 26 TypeVisitor<R,P> uses those generic roles; its API describes Void as an option when a visitor needs neither a result nor an extra parameter (Oracle Java SE 26 TypeVisitor API).

When Visitor is a good fit

  • Your structure has multiple concrete element types.
  • You need several operations that behave differently for those types, such as export, validation, reporting, or analysis.
  • The element types are expected to change less often than the operations.

Visitor can be less suitable when element types are added frequently, when operations need extensive access to private state, or when a small conditional would be clearer. Because each visitor must know the concrete types, adding a new type can ripple through visitor contracts and implementations. The Refactoring.Guru overview discusses the pattern’s applicability and trade-offs; PMI’s Disciplined Agile discussion also emphasizes its costs and context (Visitor; PMI, Disciplined Agile).

Visitor compared with a type switch or pattern matching

There is no universal winner between Visitor and a type switch or pattern matching. Compare them against the shape of your codebase:

  • How often do types change? Visitor makes adding a new operation more localized, but new element types require changes to visitor contracts and implementations.
  • How often do operations change? If operations are added often and the element set is stable, separate visitors can keep those changes out of the element classes.
  • Is the set of types closed or open? A design that needs exhaustive handling may favor a mechanism that makes missing cases visible; the best choice depends on the type model and Java features in use.
  • What does encapsulation require? If an operation needs internal state that elements do not expose, decide whether adding a suitable public operation or data view is acceptable before adopting visitors.

The sources establish Visitor’s operation-versus-type evolution trade-off, but do not establish a general verdict for modern Java pattern matching. Make the choice based on how your types and operations are likely to evolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Visitor in the Java standard library

Oracle documents TypeVisitor<R,P> as “A visitor of types, in the style of the visitor design pattern.” It is used when the kind of type is unknown at compile time; when a type’s accept method receives a visitor, the applicable visitXyz method is invoked (Oracle Java SE 26 TypeVisitor API).

The Java SE 26 API also notes that methods may be added to accommodate language structures not known to earlier versions. For that API, Oracle advises concrete visitor implementers to extend an appropriate abstract visitor class to reduce source incompatibility, while APIs should generally use the visitor interface in signatures. This is guidance for that evolving JDK API, not a universal rule for every application-level visitor. Refactoring.Guru also identifies java.nio.file.FileVisitor and SimpleFileVisitor among Java library examples (Visitor in Java).

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.