Skip to content

Visitor

Context: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements.

public interface IElement
{
void Accept(IVisitor visitor);
}
public class ConcreteElementA : IElement
{
public void Accept(IVisitor visitor) => visitor.VisitConcreteElementA(this);
}
public interface IVisitor
{
void VisitConcreteElementA(ConcreteElementA element);
}
public class ConcreteVisitor : IVisitor
{
public void VisitConcreteElementA(ConcreteElementA element) => Console.WriteLine("Visited A");
}

Abstract syntax tree (AST) processing: A compiler defines different visitors (type checker, code generator, optimizer) that traverse the AST without modifying node classes.

Example: In .NET, System.Linq.Expressions.ExpressionVisitor allows visiting expression trees. Roslyn uses visitors extensively for syntax tree analysis and transformation.