Friday, February 24, 2023

Observer Pattern

The observer pattern is a design pattern that allows objects to observe changes in the state of another object, and to receive notifications when those changes occur. Here's an example of how to implement the observer pattern in C++:

#include <iostream> #include <vector> class Observer {     public: virtual ~Observer()     {     } virtual void update(int data) = 0; }; class Subject {     public: void attach(Observer* observer)     { observers.push_back(observer); } void detach(Observer* observer)     { for (auto it = observers.begin(); it != observers.end(); ++it) { if (*it == observer)     { observers.erase(it); break; } } } void notify(int data)     { for (auto observer : observers) { observer->update(data); } }     private: std::vector<Observer*> observers; }; class ConcreteObserver : public Observer {     public: ConcreteObserver(const std::string& name) : name(name)     {     } void update(int data) override     { std::cout << "Observer " << name << " received update: " << data << std::endl; }     private: std::string name; }; int main() { Subject subject; ConcreteObserver observer1("Observer 1"); ConcreteObserver observer2("Observer 2"); ConcreteObserver observer3("Observer 3"); subject.attach(&observer1); subject.attach(&observer2); subject.attach(&observer3); subject.notify(42); subject.detach(&observer2); subject.notify(123); return 0; }

In this example, we have a Subject class that maintains a list of observers, which are objects that implement the Observer interface. The Subject class has methods for attaching and detaching observers, as well as a notify method that sends a notification to all attached observers.

The ConcreteObserver class is an implementation of the Observer interface. It simply prints out a message when it receives an update from the subject.

In the main function, we create an Subject object and three ConcreteObserver objects. We attach all three observers to the subject and then send a notification to all observers by calling the notify method on the subject. We then detach the second observer and send another notification to the remaining two observers.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...