#include <thread>
#include <iostream>
#include <vector>
using namespace std;
/*
* 观察者模式
* 定义了一种一对多的关系, 当多个观察对象同时监听一个主体对象, 主体对象发生变化时, 会通知所有的观察者, 使他们能够更新自己
*/
class Secretary;
class StockObserver {
public:
StockObserver(string name, Secretary* secretary): name(name), secretary(secretary) {}
void update();
private:
string name;
Secretary* secretary;
};
class Secretary {
public:
void add(StockObserver* observer) {
this->observers.push_back(observer);
}
void notify() {
for (auto iterator = this->observers.begin(); iterator != this->observers.end(); iterator++) {
(*iterator)->update();
}
}
string action;
private:
vector<StockObserver*> observers;
};
void StockObserver::update() {
std::cout << ": " << this->secretary->action << " boss is comming," << this->name << " stop trading!" << std::endl;
}
int main() {
Secretary* secretary = new Secretary();
StockObserver* trader1 = new StockObserver("t", secretary);
StockObserver* trader2 = new StockObserver("q", secretary);
StockObserver* trader3 = new StockObserver("z", secretary);
secretary->add(trader1);
secretary->add(trader2);
secretary->add(trader3);
secretary->action = "SOS";
secretary->notify();
return 0;
}
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
// 观察者模式(抽象类)
class SecretaryBase;
class CObserverBase {
public:
CObserverBase(string name, SecretaryBase* secretary): name(name), secretary(secretary) {}
virtual ~CObserverBase() = default;
virtual void update() = 0;
protected:
string name;
SecretaryBase* secretary;
};
class StockObserver: public CObserverBase {
public:
StockObserver(string name, SecretaryBase* secretary): CObserverBase(name, secretary) {}
virtual void update();
};
class PingpangObserver: public CObserverBase {
public:
PingpangObserver(string name, SecretaryBase* secretary): CObserverBase(name, secretary) {}
virtual void update();
};
class SecretaryBase {
public:
virtual ~SecretaryBase() = default;
virtual void add(CObserverBase* observer) = 0;
virtual void notify() = 0;
string action;
protected:
vector<CObserverBase*> observers;
};
class Secretary: public SecretaryBase {
public:
virtual void add(CObserverBase* observer) {
this->observers.push_back(observer);
}
virtual void notify() {
for (auto iterator = this->observers.begin(); iterator != this->observers.end(); iterator++) {
(*iterator)->update();
}
}
};
void StockObserver::update() {
std::cout << ": " << this->secretary->action << "boss is comming, " << this->name << " stop trading." << std::endl;
}
void PingpangObserver::update() {
std::cout << ": " << this->secretary->action << "boss is comming, " << this->name << " stop pingpang." << std::endl;
}
int main() {
SecretaryBase* secretary = new Secretary();
CObserverBase* pingpang = new PingpangObserver("tqz", secretary);
CObserverBase* trader = new StockObserver("lb", secretary);
secretary->add(pingpang);
secretary->add(trader);
secretary->action = "SOS";
secretary->notify();
delete secretary;
delete pingpang;
delete trader;
return 0;
}