观察者模式

动机
- 在软件构建过程中,我们需要为某些对象建立一种**“通知依赖关系”——一个对象(目标对象)的状态发生改变**,所有的依赖对象(观察者对象)都将得到通知。如果这样的依赖关系过于紧密,将使软件不能很好地抵御变化。
- 使用面向对象技术,可以将这种依赖关系弱化,并形成─种稳定的依赖关系。从而实现软件体系结构的松耦合。
定义
- 定义对象间的一种一对多(变化)的依赖关系,以便当一个对象(Subject)的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
- 使用面向对象的抽象,Observer模式使得我们可以独立地改变目标与观察者,从而使二者之间的依赖关系达致松耦合。
- 目标发送通知时,无需指定观察者,通知(可以携带通知信息作为参数)会自动传播。
- 观察者自己决定是否需要订阅通知,目标对象对此一无所知。
- Observer模式是基于事件的UI框架中非常常用的设计模式,也是MVC模式的一个重要组成部分。

#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Observer {
public:
Observer(){}
virtual ~Observer(){}
virtual void Notified(bool b) = 0;
};
class Student : public Observer{
public:
string name;
Student(string s) : name(s) {}
virtual Student(){}
virtual void Notified(bool b) {
if (b) {
cout << name << " is studying" << endl;
}
else {
cout << name << " is 摸鱼ing" << endl;
}
}
};
class Teacher {
public:
string name;
Teacher(string s) : name(s) {}
~Teacher(){}
bool isIn = false;
list<Observer*> observers;
void AddObserver(Observer* obs) {
observers.push_back(obs);
}
void RemoveObserver(Observer* obs) {
for (auto o : observers) {
if (o == obs) {
observers.remove(o);
}
}
}
void setBool(bool b) {
isIn = b;
if (isIn) {
cout << name << " comes in" << endl;
}
else {
cout << name << " comes out" << endl;
}
Notify(b);
}
void Notify(bool b) {
if (observers.size() == 0) return;
for (auto o : observers) {
o->Notified(b);
}
}
};
int main()
{
Student* vertin = new Student("Vertin");
Student* sonetto = new Student("Sonetto");
Teacher* miss_Z = new Teacher("Miss_Z");
miss_Z->setBool(true);
cout << "---------------------------------------" << endl;
miss_Z->setBool(false);
miss_Z->AddObserver(vertin);
miss_Z->AddObserver(sonetto);
miss_Z->setBool(true);
cout << "---------------------------------------" << endl;
miss_Z->setBool(false);
}
#include <iostream>
using namespace std;
#include "vector"
#include "string"
class Secretary;
class PlayserObserver {
public:
PlayserObserver(string name, Secretary *secretary)
:m_name(name),m_secretary(secretary) {}
void update(string action){
cout << "观察者收到action:" << action << endl;
}
private:
string m_name;
Secretary *m_secretary;
};
class Secretary{
public:
void addObserver(PlayserObserver *o){
v.push_back(o);
}
void Notify(string action) {
for (auto it : v){
it->update(action);
}
}
void setAction(string action) {
m_action = action;
Notify(m_action);
}
private:
string m_action;
vector<PlayserObserver *> v;
};
void main() {
Secretary *s1 = new Secretary;
PlayserObserver *po1 = new PlayserObserver("小张", s1);
s1->addObserver(po1);
s1->setAction("老板来了");
s1->setAction("老板走了");
cout<<"hello..."<<endl;
system("pause");
return ;
}