每日博客

观察者模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解观察者模式的动机,掌握该模式的结构;

2、能够利用观察者模式解决实际问题。

 

 

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

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

C++版

#include<iostream>
#include<string>
#include<list>
using namespace std;

class Observer {

public: virtual void moneyUp() = 0;
virtual void moneyDown() = 0;
};

class GuMin :public Observer {

private: string name;
public: GuMin(string n) {
name = n;
}

void moneyUp() {
cout << name << "买" << endl;
}
void moneyDown() {
cout << name << "大哭一场" << endl;
}

};
class Subject {
protected: list<Observer*> olist;
public:
Subject() {
}
void add(Observer *o) {
olist.push_back(o);
}
void remove(Observer *o) {
olist.remove(o);
}
virtual void up(double a) {};
virtual void down(double a) {};

};

class GuPiao :public Subject {

public:
GuPiao() {

}

void up(double a) {
if (a > 0.05) {
for (list<Observer*>::const_iterator p = olist.begin(); p != olist.cend(); ++p) {
(*p)->moneyUp();
}
}

}

void down(double a) {

if (a > 0.05) {
list<Observer*>::iterator p = olist.begin();
for (; p != olist.end(); ++p) {
(*p)->moneyDown();
}
}
}

};
int main() {

Subject *f = new GuPiao();
GuMin *g = new GuMin("股民");
f->add(g);
cout << "股票升了" << endl;
f->up(0.1);

f->down(0.001);

cout << "股票降了" << endl;
f->down(0.1);
f->down(0.001);
return 0;

}

posted @ 2021-11-04 21:01  谦寻  阅读(74)  评论(0编辑  收藏  举报