How do I implement the observer pattern in data processing pipelines with C++?

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; }

Observer Pattern C++ Data Processing Design Patterns Observer