Skip to content

Design Patterns

Visitor

Visiting all n objects takes O(n) time. Each single visit takes O(1) time (a constant amount) plus whatever that operation itself costs.

The idea, in plain English

A visitor works like a museum tour guide who knows how to talk about many different exhibits. The paintings and statues don't need to know how to describe themselves. The guide 'visits' each one and knows exactly what to say about it. In code, a visitor object carries a new operation. Each object just lets the visitor look at it, instead of implementing every possible operation itself.

How it works

  1. 1You give each kind of object an `accept(visitor)` method. It just calls the matching method on the visitor, like `visitor.visitCircle(this)`.
  2. 2You write a visitor class with one method for each kind of object it knows how to handle.
  3. 3To add a brand-new operation, you write a whole new visitor class. The original objects never need to change.

When you'd use it

Use this when you need to run several different operations over a group of related objects — shapes, file types, or parts of a parsed program. You don't want to keep editing every object's class each time you add one more operation.

Common beginner mistakes

  • When you add a new object type, add a matching method to every visitor, or that type goes silently unhandled.
  • Don't pack unrelated logic into one visitor. Split it into several focused visitors instead.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Circle area (approx): 12
Square area: 16
A circle with radius 2
A square with side 4

Not sure this is the right topic? See the learning paths → or where this leads →