观察者模式:股票提醒
当股票的价格上涨或下降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; }
实现截图: