#include <iostream> #include <vector> #include <memory> /* 在这个例子中,当股票价格发生变化时,所有的投资者都会收到通知并更新他们的状态。观察者模式使得我们可以轻松地添加或删除投资者,而不需要修改股票类的代码,从而实现了解耦和灵活性。 */ // 抽象观察者类:投资者 class Investor { public: virtual ~Investor() {} virtual void update(double price) = 0; }; // 具体观察者类:具体投资者 class ConcreteInvestor : public Investor { private: std::string name; public: ConcreteInvestor(const std::string& name) : name(name) {} void update(double price) override { std::cout << "Investor " << name << " is notified. New stock price: " << price << std::endl; } }; // 抽象主题类:股票 class Stock { public: virtual ~Stock() {} virtual void addObserver(std::shared_ptr<Investor> investor) = 0; virtual void removeObserver(std::shared_ptr<Investor> investor) = 0; virtual void notifyObservers() = 0; }; // 具体主题类:具体股票 class ConcreteStock : public Stock { private: std::vector<std::shared_ptr<Investor>> investors; double price; public: void addObserver(std::shared_ptr<Investor> investor) override { investors.push_back(investor); } void removeObserver(std::shared_ptr<Investor> investor) override { investors.erase(std::remove(investors.begin(), investors.end(), investor), investors.end()); } void notifyObservers() override { for (const auto& investor : investors) { investor->update(price); } } void setPrice(double newPrice) { price = newPrice; notifyObservers(); } }; int main() { // 创建具体股票 std::shared_ptr<ConcreteStock> stock = std::make_shared<ConcreteStock>(); // 创建具体投资者 std::shared_ptr<Investor> investor1 = std::make_shared<ConcreteInvestor>("Alice"); std::shared_ptr<Investor> investor2 = std::make_shared<ConcreteInvestor>("Bob"); // 添加投资者到股票的观察者列表中 stock->addObserver(investor1); stock->addObserver(investor2); // 修改股票价格 stock->setPrice(100.0); stock->setPrice(105.0); return 0; }