All PatternsBehavioral
Visitor
Separates algorithms from the objects on which they operate.
AST processingDocument exportReport generation
Understanding Visitor
The Visitor pattern lets you define new operations on elements of an object structure without changing the classes of the elements. It separates algorithms from the objects they operate on.
How It Works
Elements
Circle
Accept(v)
Rectangle
Accept(v)
Triangle
Accept(v)
Visitor
AreaCalc
VisitCircle()
VisitRectangle()
VisitTriangle()
Different element types
1
Element Structure
Objects with different types in a structure.
1 / 4
Basic Implementation
Area calculator visiting different shapes:
main.go
Loading editor...
Real-World Example: Document Export
Document nodes with HTML and plain text exporters:
main.go
Loading editor...