Pattern · Advanced

Visitor

Add new operations to a set of object types WITHOUT editing those types — by moving each operation into a visitor and letting elements "accept" it.

Asked atAmazonGoogleOracle
step 1 / 10
1/2Double dispatch
accept→visit
«interface»
Shape
+ accept(v)
Circle
+ accept(v)
Square
+ accept(v)
«interface»
Visitor
+ visitCircle(c)
+ visitSquare(s)
AreaVisitor
Double dispatch
1interface Shape { void accept(Visitor v); }
2interface Visitor { void visitCircle(Circle c); void visitSquare(Square s); }
3class Circle implements Shape { void accept(Visitor v){ v.visitCircle(this); } }
4class AreaVisitor implements Visitor { double visitCircle(Circle c){...} }
State
elementjust accept(v)

Shape declares a single method: accept(visitor). Circle and Square implement it — that one hook is all an element ever needs. No operation logic lives here.