目录
观察者模式(Observer Pattern)
观察者模式是一种行为型设计模式,它定义了对象间的一对多依赖关系。当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。观察者模式主要包含以下角色:
1. Subject(主题):保存对观察者的引用,并提供注册和注销观察者的方法。
2. Observer(观察者):定义一个更新接口,用于接收主题的通知。
3. ConcreteSubject(具体主题):具体实现主题,维护其状态并在状态改变时通知观察者。
4. ConcreteObserver(具体观察者):具体实现观察者,响应主题的通知并进行相应的更新。
实际应用
股票价格监控系统
-- 实现一个股票价格监控系统,当股票价格发生变化时,所有注册的观察者(例如投资者)都会收到通知。
#include <iostream>
#include <vector>
#include <string>
#include <memory>
// 观察者接口
class Observer {
public:
virtual void update(const std::string& stockName, float price) = 0;
};
// 主题接口
class Subject {
public:
virtual void registerObserver(std::shared_ptr<Observer> observer) = 0;
virtual void removeObserver(std::shared_ptr<Observer> observer) = 0;
virtual void notifyObservers() = 0;
};
// 具体主题
class Stock : public Subject {
private:
std::string name;
float price;
std::vector<std::shared_ptr<Observer>> observers;
public:
Stock(const std::string& name, float price) : name(name), price(price) {}
void setPrice(float newPrice) {
price = newPrice;
notifyObservers();
}
float getPrice() const {
return price;
}
void registerObserver(std::shared_ptr<Observer> observer) override {
observers.push_back(observer);
}
void removeObserver(std::shared_ptr<Observer> observer) override {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notifyObservers() override {
for (auto& observer : observers) {
observer->update(name, price);
}
}
};
// 具体观察者
class Investor : public Observer {
private:
std::string name;
public:
Investor(const std::string& name) : name(name) {}
void update(const std::string& stockName, float price) override {
std::cout << "Investor " << name << " is notified that " << stockName << " price changed to " << price << std::endl;
}
};
// 客户端代码
int main() {
auto stock = std::make_shared<Stock>("AAPL", 150.0);
auto investor1 = std::make_shared<Investor>("Alice");
auto investor2 = std::make_shared<Investor>("Bob");
stock->registerObserver(investor1);
stock->registerObserver(investor2);
stock->setPrice(155.0);
stock->setPrice(160.0);
stock->removeObserver(investor1);
stock->setPrice(165.0);
return 0;
}
发布-订阅系统
-- 实现一个简单的发布-订阅系统,当发布者发布新消息时,所有订阅者都会收到通知。
#include <iostream>
#include <vector>
#include <string>
#include <memory>
// 观察者接口
class Subscriber {
public:
virtual void update(const std::string& message) = 0;
};
// 主题接口
class Publisher {
public:
virtual void registerSubscriber(std::shared_ptr<Subscriber> subscriber) = 0;
virtual void removeSubscriber(std::shared_ptr<Subscriber> subscriber) = 0;
virtual void notifySubscribers() = 0;
};
// 具体主题
class NewsPublisher : public Publisher {
private:
std::string latestNews;
std::vector<std::shared_ptr<Subscriber>> subscribers;
public:
void publishNews(const std::string& news) {
latestNews = news;
notifySubscribers();
}
void registerSubscriber(std::shared_ptr<Subscriber> subscriber) override {
subscribers.push_back(subscriber);
}
void removeSubscriber(std::shared_ptr<Subscriber> subscriber) override {
subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), subscriber), subscribers.end());
}
void notifySubscribers() override {
for (auto& subscriber : subscribers) {
subscriber->update(latestNews);
}
}
};
// 具体观察者
class ConcreteSubscriber : public Subscriber {
private:
std::string name;
public:
ConcreteSubscriber(const std::string& name) : name(name) {}
void update(const std::string& message) override {
std::cout << "Subscriber " << name << " received: " << message << std::endl;
}
};
// 客户端代码
int main() {
auto publisher = std::make_shared<NewsPublisher>();
auto subscriber1 = std::make_shared<ConcreteSubscriber>("Alice");
auto subscriber2 = std::make_shared<ConcreteSubscriber>("Bob");
publisher->registerSubscriber(subscriber1);
publisher->registerSubscriber(subscriber2);
publisher->publishNews("Breaking News: Observer Pattern in Action!");
publisher->publishNews("Latest Update: New Design Patterns Discovered!");
publisher->removeSubscriber(subscriber1);
publisher->publishNews("Exclusive: Observer Pattern Simplified!");
return 0;
}
总结
观察者模式帮助我们定义了对象间的一对多依赖关系,使得对象之间的通信变得更加灵活和可扩展。