观察者模式C++
一、今日学习内容
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
c++:
#include<iostream> #include<list> using namespace std; class MyObserver { public: virtual void response(int rate) {}; }; class MySubject { protected: list<MyObserver*>observers; public: /*注册方法*/ void attach(MyObserver*observer) { observers.push_back(observer); }; /*注销方法*/ void detach(MyObserver* observer) { observers.remove(observer); } /*抽象通知方法*/ virtual void change(int rate) = 0; }; class Stock : public MySubject { public: void change(int rate) { list<MyObserver*>::iterator iter = observers.begin(); for (; iter != observers.end(); iter++) (*iter)->response(rate); } }; class Holders :public MyObserver { public: void response(int rate) { if (rate >= 5) { cout << "股票上涨,购买股票" << endl; } else if (rate <= -5) { cout << "股票下跌,大哭一场" << endl; } else { cout << "股票还比较稳定哦~" << endl; } } }; int main() { MySubject* subject = new Stock(); MyObserver*obs1 = new Holders(); subject->attach(obs1); cout << "----------------------股票上涨-----------------------" << endl; subject->change(5); cout << endl; cout << "----------------------股票下跌-----------------------" << endl; subject->change(-5); cout << endl; cout << "----------------------股票稳定-----------------------" << endl; subject->change(4); cout << endl; }
截图: