#include "stdafx.h" #include <iostream> #include <vector> #include <string> using namespace std; class Observer { public: virtual void Update() = 0; virtual ~Observer(){} }; class Subject { public: virtual ~Subject(){} virtual void Attach(Observer* observer) { _observers.push_back(observer); } virtual void Detach(Observer* observer) { vector<Observer*>::iterator it = find(_observers.begin(), _observers.end(), observer); _observers.erase(it); } virtual void Notify() { for each (Observer* o in _observers) { o->Update(); } } private: vector<Observer*> _observers = vector<Observer*>(); }; class ConcreteSubject :public Subject { public : ~ConcreteSubject(){} string SubjectState; }; class ConcreteObserver :public Observer { private: string _name; string _ObserverState; ConcreteSubject *_pSubject; public: ConcreteObserver( ConcreteSubject *subject, string name) { _pSubject = subject; _name = name; } virtual void Update() { _ObserverState = _pSubject->SubjectState; cout << "观察者:"<<_name<<" 当前状态:"<<_ObserverState << endl; } };
// ObserverPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Observer.h" int _tmain(int argc, _TCHAR* argv[]) { ConcreteSubject *s = new ConcreteSubject(); s->Attach(new ConcreteObserver(s, "x")); s->Attach(new ConcreteObserver(s, "y")); s->SubjectState = "老板回来了"; s->Notify(); getchar(); return 0; }
原文:http://blog.csdn.net/wwwdongzi/article/details/26813805