Sobes.tech
Junior — Middle

What is the main function of the Visitor pattern in OOP?

sobes.tech AI

Answer from AI

The Visitor pattern in object-oriented programming allows separating algorithms from the data structures they operate on. The main function of the pattern is to add new operations to objects without changing their classes.

This is achieved by creating a separate "visitor" object that implements the required operations, and an "element" that accepts the visitor and calls the appropriate method.

Example in C++:

class Visitor {
public:
    virtual void visit(class ElementA* element) = 0;
    virtual void visit(class ElementB* element) = 0;
};

class Element {
public:
    virtual void accept(Visitor* visitor) = 0;
};

class ElementA : public Element {
public:
    void accept(Visitor* visitor) override {
        visitor->visit(this);
    }
};

class ConcreteVisitor : public Visitor {
public:
    void visit(ElementA* element) override {
        // Implementation of operation for ElementA
    }
    void visit(ElementB* element) override {
        // Implementation of operation for ElementB
    }
};

Thus, new operations can be added without changing the element classes.