BehavioralC++verifiedVerified

Visitor Pattern in C++

Lets you add new operations to an object structure without modifying the objects themselves, by separating the algorithm from the object structure it operates on.

How to Implement the Visitor Pattern in C++

1Step 1: Define the Visitor interface

class ShapeVisitor {
public:
    virtual ~ShapeVisitor() = default;
    virtual void visitCircle(const Circle& c) = 0;
    virtual void visitRectangle(const Rectangle& r) = 0;
};

2Step 2: Element interface with accept method

class Shape {
public:
    virtual ~Shape() = default;
    virtual void accept(ShapeVisitor& visitor) const = 0;
};

class Circle : public Shape {
    double radius_;
public:
    explicit Circle(double r) : radius_(r) {}
    double radius() const { return radius_; }
    void accept(ShapeVisitor& visitor) const override { visitor.visitCircle(*this); }
};

class Rectangle : public Shape {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double width() const { return w_; }
    double height() const { return h_; }
    void accept(ShapeVisitor& visitor) const override { visitor.visitRectangle(*this); }
};

3Step 3: Concrete visitor: area calculator

class AreaCalculator : public ShapeVisitor {
    double total_ = 0;
public:
    void visitCircle(const Circle& c) override {
        total_ += 3.14159 * c.radius() * c.radius();
    }
    void visitRectangle(const Rectangle& r) override {
        total_ += r.width() * r.height();
    }
    double total() const { return total_; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(5.0));
    shapes.push_back(std::make_unique<Rectangle>(3.0, 4.0));

    AreaCalculator calc;
    for (const auto& s : shapes) s->accept(calc);

    std::cout << "Total area: " << calc.total() << "\n";
}

Visitor Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Visitor Pattern in the Real World

Think of a tax auditor visiting different types of businesses—a restaurant, a law firm, a retail shop. The auditor (visitor) knows exactly what to examine at each type of business and applies the appropriate inspection procedure. The businesses (elements) simply let the auditor in; they don't change their own operations to accommodate the audit.