标签:style blog http io ar color os sp for
观察者模式又叫发布订阅模式(publish/subscribe)、模型视图模式(model/view)、源/监听器模式(source/listener),它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。下面是不同编程语言实现的实例。
package com.sample; import java.util.List; import java.util.ArrayList; public class ObserverDemo { public static void main(String[] args) { Subject subject = new Subject(); Observer observer = new Observer(); subject.attach(observer); subject.notify("hello"); } } class Subject { private List<Observer> observerList = new ArrayList<Observer>(); public void attach(Observer observer) { observerList.add(observer); System.out.println("attached an observer"); } public void detach(Observer observer) { observerList.remove(observer); } public void notify(String state) { for (Observer observer : observerList) { observer.update(state); } } } class Observer { public void update(String state) { System.out.println("state is: " + state); } }
observer.h
#ifndef _OBSERVER_H_ #define _OBSERVER_H_ #include <string> #include <list> using namespace std; class Subject; class Observer { public: void update(string state); }; class Subject { public: void notify(string state); void attach(Observer*); void Detach(Observer*); private: list<Observer*> observerList; } #endif
observer.cpp
#include <iostream> #include <algorithm> #include "observer.h" void Observer::update(string state) { cout<<"state is: "<<state<<endl; } void Subject::attach(Observer* pobs) { this->observerList.push_back(pobs); cout<<"attach an observer\n"; } void Subject::detach(Observer* pobs) { list<Observer*>::iterator iter; iter = find(observerList.begin(), observerList.end(), pobs); if (iter != observerList.end()) { observerList.erase(iter); } cout<<"detach an observer\n"; } void Subject::notify(string state) { list<Observer*>::iterator iter = this->observerList.begin(); for (; iter != observerList.end(); iter++) { (*iter)->update(state); } } Subject::~Subject() { list<Observer*>::iterator iter = this->observerList.begin(); for (; iter != observerList.end(); iter++) { delete *iter; } observerList.clear(); } int main(int argc, char** argv) { Observer* p1 = new Observer(); Observer* p2 = new Observer(); Observer* p3 = new Observer(); Subject* pSubject = new Subject(); pSubject->attach(p1); pSubject->attach(p2); pSubject->attach(p3); pSubject->notify("hello"); return 0; }
http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/feilv/p/4151552.html