软件设计实验21

.实验 21:观察者模式

[实验任务一]:股票提醒

当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。

#include<iostream>
#include<list>
#include<string>
using namespace std;
//抽象观察者
class Observer{
protected:
    string name;
public:
    virtual void buy()=0;
    virtual void cry()=0;
};
//具体观察者
class Gumin:public Observer{
public:
    Gumin(string name){
        this->name=name;
    }
    void buy(){
        cout<<"股民"<<name<<"买了一些股票"<<endl;
    }
    void cry(){
        cout<<"股民"<<name<<"哭了"<<endl;
    }
};
//抽象主题类
class Subject{
protected:
    list<Observer*> observers;
public:
    void attach(Observer *obs){
        observers.push_back(obs);
    }
    void detach(Observer *obs){
        observers.remove(obs);
    }
    virtual void up()=0;
    virtual void down()=0;
};
//具体主题类
class Gufen:public Subject{
public:
    void up(){
        cout<<"*****股份上涨3%*****"<<endl;
        list<Observer*>::iterator iter = observers.begin();
        for(; iter != observers.end(); iter++)
            (*iter)->buy();
    }
    void down(){
        cout<<"*****股份下跌5%*****"<<endl;
        list<Observer*>::iterator iter = observers.begin();
        for(; iter != observers.end(); iter++)
            (*iter)->cry();
    }
};
//测试函数
int main(){
    Observer *obs1,*obs2;
    obs1=new Gumin("安安");
    obs2=new Gumin("妍妍");
    Subject *sub;
    sub=new Gufen();
    sub->attach(obs1);
    sub->attach(obs2);
    sub->up();
    sub->down();
}

  

posted @ 2022-11-02 08:11  Lindseyyip  阅读(27)  评论(0编辑  收藏  举报