• 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;
    }

    实现截图:

  • 相关阅读:
    过河问题 (Standard IO)
    单词分类 (Standard IO)
    C#综合揭秘——细说多线程(上)
    使用NPOI导入导出标准Excel
    C# 转义字符 ''反斜杠
    ref和out的区别
    抽象类接口的区别
    方法签名
    SQL Server的通用分页存储过程 未使用游标,速度更快!
    SQL Server存储过程Return、output参数及使用技巧
  • 原文地址:https://www.cnblogs.com/marr/p/15598506.html
Copyright © 2020-2023  润新知