How do I implement the observer pattern in embedded devices with C++?

The Observer Pattern is a design pattern used to create a subscription model to allow multiple objects (observers) to listen and react to events or changes in another object (the subject). This pattern is especially useful in embedded systems where resource constraints and efficiency are a concern.

Implementing the Observer Pattern in Embedded C++

Below is a simple example of how to implement the Observer Pattern in C++. In this example, we have a subject class that maintains a list of observers, and observers can register or unregister themselves to the subject.

class Observer { public: virtual void update(int value) = 0; // Pure virtual function for observers to implement }; class Subject { private: std::vector observers; // List of observers int state; // State that observers are interested in public: void attach(Observer* observer) { observers.push_back(observer); // Add observer to the list } void detach(Observer* observer) { observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end()); // Remove observer } void setState(int value) { state = value; // Update state notifyObservers(); // Notify all observers of the change } void notifyObservers() { for (auto observer : observers) { observer->update(state); // Notify each observer } } }; // Concrete observer implementation class ConcreteObserver : public Observer { private: std::string name; public: ConcreteObserver(std::string name) : name(name) {} void update(int value) override { std::cout << "Observer " << name << " updated with new value: " << value << std::endl; } }; // Example usage int main() { Subject subject; ConcreteObserver observer1("Observer 1"); ConcreteObserver observer2("Observer 2"); subject.attach(&observer1); subject.attach(&observer2); subject.setState(10); // Change subject state and notify observers subject.detach(&observer1); // Detach observer1 subject.setState(20); // Change state again return 0; }

observer pattern C++ embedded systems design pattern subject observer notify update