Observer mode of C++ implementation design mode

What is the observer pattern?

Observer mode is a one-to-many relationship. When the state of an object changes, all objects that depend on it are notified and automatically updated. Its subject is the publisher of the notification. It does not need to know who is its observer when sending out the notification. Any number of observers can subscribe and receive the notification, separating the observer from the observed object.

Without further ado, let's go to the code:

#include <iostream>  
#include <vector>  
  
using namespace std;  
  
// 观察者接口  
class Observer {  
public:  
    virtual void update() = 0;  
};  
  
// 主题接口  
class Subject {  
public:  
    virtual void attach(Observer* observer) = 0;  
    virtual void detach(Observer* observer) = 0;  
    virtual void notify() = 0;  
};  
  
// 具体主题实现  
class ConcreteSubject : public Subject {  
private:  
    vector<Observer*> observers;  
public:  
    void attach(Observer* observer) {  
        observers.push_back(observer);  
    }  
  
    void detach(Observer* observer) {  
        for (int i = 0; i < observers.size(); i++) {  
            if (observers[i] == observer) {  
                observers.erase(observers.begin() + i);  
                break;  
            }  
        }  
    }  
  
    void notify() {  
        for (int i = 0; i < observers.size(); i++) {  
            observers[i]->update();  
        }  
    }  
  
    void stateChanged() {  
        notify();  
    }  
};  
  
// 具体观察者实现  
class ConcreteObserver : public Observer {  
private:  
    Subject* subject;  
public:  
    ConcreteObserver(Subject* subject) {  
        this->subject = subject;  
        subject->attach(this);  
    }  
  
    ~ConcreteObserver() {  
        subject->detach(this);  
    }  
  
    void update() {  
        // 观察者收到通知后执行的操作  
        cout << "Subject changed!" << endl;  
    }  
};  
  
int main() {  
    ConcreteSubject subject;  
    ConcreteObserver observer1(&subject);  
    ConcreteObserver observer2(&subject);  
    ConcreteObserver observer3(&subject);  
  
    subject.stateChanged(); // 触发通知,观察者更新  
  
    return 0;  
}

In the above code, ​Observer​is the observer interface and ​Subject​is the subject interface. ​​​​Is​ConcreteSubject​ the specific theme implementation, which maintains a list of observers and notifies all observers when the state changes. is a​ConcreteObserver​ concrete observer implementation that performs a specific action when notified.

In the main function, we create an ​ConcreteSubject​instance of and ​ConcreteObserver​attach three instances of to the topic. Then, when the state of the subject changes, all attached observers are notified and act accordingly.

Guess you like

Origin blog.csdn.net/renhui1112/article/details/131820204