SOLID & Design Patterns Interview Question #46

What is the Visitor Pattern?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

The Visitor Pattern separates operations from the object structure on which they operate. Objects accept a visitor, and different visitors can implement new operations without modifying every element class.

Detailed Explanation

The Visitor Pattern separates operations from the object structure on which they operate. Objects accept a visitor, and different visitors can implement new operations without modifying every element class.

Visitor is most useful when the object structure is relatively stable but many operations must be added. It is less attractive when new element types are added frequently because each visitor may then require changes.

Code Example

public interface IShapeVisitor
{
    void Visit(Circle circle);
    void Visit(Rectangle rectangle);
}

public interface IShape
{
    void Accept(IShapeVisitor visitor);
}