The Visitor Pattern is a design pattern that allows you to separate an algorithm from the object structure it operates on. This is particularly useful in processing data in pipelines, as it lets you define new operations without modifying the existing code structure.
Below is an example of how to implement the Visitor Pattern in C++ for a simple data processing pipeline.
#include
#include
// Forward declarations
class ConcreteVisitor;
// Element interface
class Element {
public:
virtual void accept(ConcreteVisitor& visitor) = 0;
};
// Concrete Elements
class DataElementA : public Element {
public:
void accept(ConcreteVisitor& visitor) override;
void processA() {
std::cout << "Processing Data from Element A" << std::endl;
}
};
class DataElementB : public Element {
public:
void accept(ConcreteVisitor& visitor) override;
void processB() {
std::cout << "Processing Data from Element B" << std::endl;
}
};
// Visitor interface
class Visitor {
public:
virtual void visit(DataElementA& element) = 0;
virtual void visit(DataElementB& element) = 0;
};
// Concrete Visitor
class ConcreteVisitor : public Visitor {
public:
void visit(DataElementA& element) override {
element.processA();
}
void visit(DataElementB& element) override {
element.processB();
}
};
void DataElementA::accept(ConcreteVisitor& visitor) {
visitor.visit(*this);
}
void DataElementB::accept(ConcreteVisitor& visitor) {
visitor.visit(*this);
}
int main() {
std::vector elements;
elements.push_back(new DataElementA());
elements.push_back(new DataElementB());
ConcreteVisitor visitor;
for (Element* element : elements) {
element->accept(visitor);
}
// Cleanup
for (Element* element : elements) {
delete element;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?