首页 > 代码库 > 观察者模式
观察者模式
观察者模式又叫发布订阅模式(publish/subscribe)、模型视图模式(model/view)、源/监听器模式(source/listener),它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。下面是不同编程语言实现的实例。
1、java实现
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); }}
2、C++实现
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;}
3、javascript实现
http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html
观察者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。