---
title: "23种设计模式之观察者模式"
author: "lynnwoo"
date: "2010-10-22T14:45:10Z"
tags: ["Java", "UML", "设计模式"]
categories: ["编程语言"]
slug: "23"
draft: false
lastmod: "2010-10-22T14:51:57Z"
id: 791516
url: "https://lynnwoo.iteye.com/blog/791516"
---

观察者模式(Observer)：定义对象间的一种一对多的依赖关系，以便当一个对象的状态发生改变时，所有依赖于它的对象都得到通知并自动刷新。

Observer 观察者
Observable 被观察者

UML图：

![](http://dl.iteye.com/upload/attachment/335675/6b2acc4e-21ac-3eec-b163-cbbc558280eb.gif)



```java

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;
	}
}


```



```java

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...");
	}

}

```



```java

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...");
	}

}

```



```java

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...