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