---
title: "Observer观察者模式的理解"
author: "rickyboy"
date: "2010-01-12T17:50:47Z"
tags: []
categories: ["企业架构"]
slug: "observer"
draft: false
lastmod: "2010-01-12T22:49:12Z"
id: 568605
url: "https://rickyboy.iteye.com/blog/568605"
---

观察者模式在不仅在java SWT中还是spring hibernate 应用都是非常广泛的，下面就我的理解做个记录。
首先要理解一些概念是必须的
事件源：事件源就是一个事件发生的组件，例如按钮，面板，在spring中可以表现为容器。

事件：我们都知道当我们点击一下按钮就是一个事件发生了。在具体表现为ActionEvent类。
比如时钟Timer类发生定时性动作时。

监听器：当某个事件发生的时候，监听器就会监听到，来进行相应的动作。当然一个容器有可能既是事件源。
下面是一个spring的观察者模式的事件的例子，
在spring中要想具有监听器功能就必须继承ApplicationListener
事件就要实现ApplicationEvent



下面是我实现的例子：

配置文件bean-config.xml


```java

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" 
  "http://www.springframework.org/dtd/spring-beans.dtd"> 

<beans> 
 <bean id="emailer" class="com.starit.bean.EmailBean">
<property name="blackList">
<list>
<value>black@list.org</value>
<value>white@list.org</value>
<value>john@doe.org</value>
</list>
</property>
</bean>
<bean id="blackListListener" class="com.starit.bean.BlackListNotifier">
<property name="notificationAddress">
<value>spam@list.org</value>
</property>
</bean>
</beans>

```

监听器类

```java


package com.starit.bean;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class BlackListNotifier implements ApplicationListener {   
	/** notification address */  
	private String notificationAddress;
  
	public void setNotificationAddress(String notificationAddress) {   
	this.notificationAddress = notificationAddress;   
	}   
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof BlackListEvent) {   
			    System.out.println(((BlackListEvent) event).getEmail().getBlackList());
		}		
	}
}
```


触发事件类


```java

package com.starit.bean;
import org.springframework.context.ApplicationEvent;

public class BlackListEvent extends ApplicationEvent{
	private static final long serialVersionUID = 1L;
	private EmailBean email = null;
	public BlackListEvent(Object o) {   
        super(o); 
    }  
    public BlackListEvent(Object source, EmailBean object) {
		super(source);
		this.setEmail(object);
	}
	public void setEmail(EmailBean email) {
		this.email = email;
	}
	public EmailBean getEmail() {
		return email;
	}
```


事件源bean类


```java
package com.starit.bean;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class EmailBean implements ApplicationContextAware {  
	
	private ApplicationContext ctx = null;
	/** the blacklist */  
	private List blackList;   
	public void setBlackList(List blackList){   
	    this.blackList = blackList;   
	}   
	public void setApplicationContext(ApplicationContext ctx) {   
	    this.ctx = ctx;   
	}
	public List getBlackList() {
		return blackList;
	}
    public void sendEmail(String address, String text){    
	    BlackListEvent evt = new BlackListEvent(address, (EmailBean)ctx.getBean("emailer"));   
	    ctx.publishEvent(evt);    
	}   
} 
```


测试类如下：

```java

package com.starit.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test {
	public static void main(String args[]) {
		ApplicationContext context = new FileSystemXmlApplicationContext("beans-config.xml");
		EmailBean emailBean = (EmailBean)context.getBean("emailer");
		emailBean.sendEmail("black@list.org","1212");
	}
}
```


以上的实现的步骤如下：
1.注册监听器。
2.事件源容器通过ctx.publishEvent(evt);触发事件 。
3.这时候我们的监听器就会能够监听到这个事件，就能够触发相应的动作。
总结：
程序中容器是事件源。也就是观察者模式中的主体对象。实现ApplicationListener接口的是监听器，也就是Observer模式中的观察者。实现ApplicationEvent是一个事件，
ps：http://www.iteye.com/topic/1292 事件模型
    http://www.iteye.com/topic/522171  AWT事件模型
    http://www.iteye.com/topic/519498  很好理解spring监听器的例子
    http://www.iteye.com/topic/102068 观察者模式剖析