#include <iostream>
#include <list>
#include <string>
using namespace std;
class ISubject;
class IObserver;
class Subject;
class Observer;
class ISubject {
private:
list<IObserver*> observerList;
public:
void AddObserver(IObserver *obs) {
observerList.push_back(obs);
};
void RemoveObserver(IObserver *obs) {
observerList.remove(obs);
};
virtual void Notified(IObserver *) = 0;
void Update() {
for (auto ob : observerList)
{
if (ob != NULL) {
Notified(ob);
}
}
}
};
class IObserver {
public:
virtual void Received(ISubject *) = 0;
};
// 实例:发布者
class Subject :public ISubject
{
public:
Subject() :ISubject() { };
void Notified(IObserver *obs) {
obs->Received(this);
}
};
// 实例:接收(观察)者
class Observer :public IObserver
{
public:
Observer(string& n) {
name = n;
};
void Received(ISubject *sub) {
cout << "this is " + name + " OBer, Received.
";
}
private:
string name;
};
int main() {
string val = "1";
Observer *obs1 = new Observer(val);
val = "2";
Observer *obs2 = new Observer(val);
val = "3";
Observer *obs3 = new Observer(val);
Subject *sub = new Subject();
// 订阅消息
sub->AddObserver(obs1);
sub->AddObserver(obs2);
sub->AddObserver(obs3);
// 发布消息
sub->Update();
cout << "///////////////////////////////
";
sub->RemoveObserver(obs2);
sub->Update();
cout << "///////////////////////////////
";
/*
this is 1 OBer, Received.
this is 2 OBer, Received.
this is 3 OBer, Received.
///////////////////////////////
this is 1 OBer, Received.
this is 3 OBer, Received.
///////////////////////////////
*/
system("pause");
return 0;
}