ITeye博客

23种设计模式之观察者模式

lynnwoo · 2010-10-22 14:45 · 设计模式 · 编程语言 · Java · UML · 设计模式 · Markdown

观察者模式(Observer):定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新。

Observer 观察者 Observable 被观察者

UML图:


package org.example.patterns.observerPattern;

import java.util.Observable;

public class Thief extends Observable {

	final static String OUT_OF_HOUSE = "The thief is out and going to steal something...";
	final static String IN_HOUSE = "The thief stay at home...";

	private String state = IN_HOUSE;

	public synchronized void setState(String state) {

		this.state = state;
		System.out.println(state);
		this.setChanged();
		this.notifyObservers();
	}
	
	public String getState(){
		return state;
	}
}



package org.example.patterns.observerPattern;

import java.util.Observable;
import java.util.Observer;

public class PoliceA implements Observer{

	public void update(Observable o, Object arg) {
		System.out.println("notify policeA...");
	}

}


package org.example.patterns.observerPattern;

import java.util.Observable;
import java.util.Observer;


public class PoliceB implements Observer{

	public void update(Observable o, Object arg) {
		System.out.println("Notify policeB...");
	}

}


package org.example.patterns.observerPattern;

public class Main {

	public static void main(String[] args) {
		Thief t = new Thief();		
		t.addObserver(new PoliceB());
		t.addObserver(new PoliceA());
		
		t.setState(Thief.OUT_OF_HOUSE);
	}

}

运行结果: The thief is out and going to steal something... notify policeA... Notify policeB...

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。