标签:c++ 设计模式
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。#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; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/26813805