一,核心思想:消息订阅,
主题:subject
观察者:observe
场景举例:
我(observe)关注抖音一条小团团(subject)
小团团一有动静,立马就推送给我
场景举例:
广播电台(subject):天天放养猪方法
我(observe)关注了该频道
电台天天给我推送
场景举例:新闻联播天天放,你看不看它都在放。你关注它就看,不关注就不看
二,关键在于代码怎么写,怎么关注
QT开发举例
使用举例:比如Qt
//subject:主题
while(1)
{
emit message("hello");
}
//observer:观察者
connect()
连接上面的信号,我就接收它的消息
disconnect()
断开上面的信号,我就不接收
c++开发举例
一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象状态发生改变时,它的所有依赖者(观察者)都会收到通知并自动更新。
#include <iostream>
#include <vector>
// 观察者接口
class Observer {
public:
virtual void Observer() {}
virtual void update(const std::string& message) = 0;
};
// 具体观察者
class ConcreteObserver : public Observer {
public:
ConcreteObserver(const std::string& name) : name_(name) {}
void update(const std::string& message) override {
std::cout << name_ << " received message: " << message << std::endl;
}
private:
std::string name_;
};
// 主题接口
class Subject {
public:
virtual void Subject() {}
virtual void attach(Observer* observer) = 0;
virtual void detach(Observer* observer) = 0;
virtual void notifyObservers(const std::string& message) = 0;
};
// 具体主题
class ConcreteSubject : public Subject {
public:
void attach(Observer* observer) override {
observers_.push_back(observer);
}
void detach(Observer* observer) override {
auto it = std::find(observers_.begin(), observers_.end(), observer);
if (it != observers_.end()) {
observers_.erase(it);
}
}
void notifyObservers(const std::string& message) override {
for (auto* observer : observers_) {
observer->update(message);
}
}
private:
std::vector<Observer*> observers_;
};
int main() {
ConcreteSubject* subject = new ConcreteSubject();
Observer* observer1 = new ConcreteObserver("Observer 1");
Observer* observer2 = new ConcreteObserver("Observer 2");
Observer* observer3 = new ConcreteObserver("Observer 3");
subject->attach(observer1);
subject->attach(observer2);
subject->attach(observer3);
subject->notifyObservers("Hello, observers!");
subject->detach(observer2);
subject->notifyObservers("Goodbye, observers!");
delete observer1;
delete observer2;
delete observer3;
delete subject;
return 0;
}