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 on which it operates. Use when many distinct, unrelated operations need to be performed on an object structure and you want to avoid polluting element classes with those operations.
Examples:
- A geographic graph of cities, industries, and sightseeing areas needs XML export added without modifying each node class. A Visitor (XmlExportVisitor) declares a visit method for each node type; each node implements accept(visitor), calling visitor.visitCity(this) or visitor.visitIndustry(this). Adding a JSON export visitor later requires only a new visitor class — no changes to the graph nodes.
class Visitor {
public:
virtual void VisitAssignNode(AssignNode*) = 0;
virtual void VisitVarNode(VarNode*) = 0;
};
class Node {
public:
virtual void Accept(Visitor& v) = 0;
};
class AssignNode : public Node {
void Accept(Visitor& v) override { v.VisitAssignNode(this); }
};
class TypeCheckingVisitor : public Visitor {
void VisitAssignNode(AssignNode* n) override { /* type check */ }
};