观察者模式,详情请看:
http://en.wikipedia.org/wiki/Observer_pattern
main.cpp:
#include "observer_pattern.h"
student s[5];
teacher t[5];
void tell_us_what_you_know() {
for (int i = 0; i < 5; i++) {
cout << "Student_" << i << " knows " << s[i].what_i_know() << endl;
}
for (int i = 0; i < 5; i++) {
cout << "Teacher_" << i << " knows " << t[i].what_i_know() << endl;
}
cout << endl;
}
int main() {
subject TeachingAffairsOffice;
for (int i = 0; i < 5; i++) {
TeachingAffairsOffice.registerObserver(s + i);
TeachingAffairsOffice.registerObserver(t + i);
}
TeachingAffairsOffice.notifyObserver("the students of Grade 13 are all given an F in mid-term examination.");
tell_us_what_you_know();
TeachingAffairsOffice.notifyObserver("it's just a joke.");
tell_us_what_you_know();
TeachingAffairsOffice.notifyObserver("it's a real joke");
tell_us_what_you_know();
}
observer_pattern.h:
#ifndef __OBSERVER_PATTERN_H
#define __OBSERVER_PATTERN_H
#include <iostream>
#include <string>
#include <list>
using namespace std;
class observer {
public:
observer() {
message = "nothing";
}
void notify(string new_message) {
message = new_message;
}
string what_i_know() {
return message;
}
private:
string message;
};
class student: public observer {};
class teacher: public observer {};
class subject {
public:
void registerObserver(observer* new_observer) {
for (iter = l.begin(); iter != l.end(); iter++) {
if (*iter == new_observer) {
cout << "The observer you want to register already exists!" << endl;
return;
}
}
l.push_back(new_observer);
}
void unregisterObserver(observer* the_observer) {
for (iter = l.begin(); iter != l.end(); iter++) {
if (*iter == the_observer) {
l.erase(iter);
return;
}
}
cout << "The observer you want to unregister does not exists!" << endl;
}
void notifyObserver(string message) {
for (iter = l.begin(); iter != l.end(); iter++) {
(*iter)->notify(message);
}
}
private:
list<observer*> l;
list<observer*>::iterator iter;
};
#endif