zoukankan      html  css  js  c++  java
  • 2021.12.13(观察者模式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;
    }

    实现截图:

  • 相关阅读:
    旧梦重温
    树莓派改用中山大学软件源
    [翻译]lpeg入门教程
    为python-sproto添加map支持
    玩家回档原因分析
    为sproto添加python绑定
    如何快速编写Vim语法高亮文件
    windows调试器尝鲜
    休斯顿,我们遇到了一个问题
    糟糕的十一月
  • 原文地址:https://www.cnblogs.com/marr/p/15598506.html
Copyright © 2011-2022 走看看