The Observer Pattern is a behavioral design pattern that allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them automatically of state changes. This pattern is particularly useful in data processing pipelines where multiple stages of processing can act on the output of previous stages.
In C++, you can implement the observer pattern easily with the help of standard template libraries and classes. Below is a simple example of how you can set up an observer pattern in a data processing pipeline.
#include <iostream>
#include <vector>
#include <algorithm>
// Observer Interface
class Observer {
public:
virtual void update(int data) = 0;
};
// Subject Class
class Subject {
private:
std::vector observers;
public:
void addObserver(Observer* observer) {
observers.push_back(observer);
}
void removeObserver(Observer* observer) {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notifyObservers(int data) {
for (Observer* observer : observers) {
observer->update(data);
}
}
};
// Concrete Observer
class ConcreteObserver : public Observer {
public:
void update(int data) override {
std::cout << "Data received: " << data << std::endl;
}
};
int main() {
Subject subject;
ConcreteObserver observer1;
ConcreteObserver observer2;
subject.addObserver(&observer1);
subject.addObserver(&observer2);
// Simulate data processing
subject.notifyObservers(10);
subject.notifyObservers(20);
subject.removeObserver(&observer1);
subject.notifyObservers(30);
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?