每日总结
软件设计模式 观察者模式:
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class AbstractObserver {
public:
virtual void response(int n) = 0;
};
class ConcreteObserver :public AbstractObserver {
public:
string name;
ConcreteObserver(string name) {
this->name = name;
}
void response(int n) {
if (n == 1) {
cout << name << "买入!" << endl;
}
else {
cout << name << " 大哭" << endl;
}
};
};
class AbstractSubject {
public:
vector<ConcreteObserver>* observers = new vector<ConcreteObserver>;
void attch(ConcreteObserver observer) {
observers->push_back(observer);
};
void detach(ConcreteObserver observer) {
};
virtual void up() = 0;
virtual void down() = 0;
};
class ConcreteSubject :public AbstractSubject {
public:
void up() {
cout << "股票上涨" << endl;
for (int i = 0; i < observers->size(); i++) {
observers->at(i).response(1);
}
}
void down() {
cout << "股票下跌" << endl;
for (int i = 0; i < observers->size(); i++) {
observers->at(i).response(0);
}
;
}
};
int main() {
AbstractSubject* as = new ConcreteSubject();
ConcreteObserver ao1 = ConcreteObserver("小云");
ConcreteObserver ao2 = ConcreteObserver("小王");
ConcreteObserver ao3 = ConcreteObserver("华腾");
ConcreteObserver ao4 = ConcreteObserver("三石");
as->attch(ao1);
as->attch(ao2);
as->attch(ao3);
as->attch(ao4);
as->up();
cout << "*******************" << endl;
as->down();
}