1,解释;
java事件机制包括三个部分:事件、事件监听器、事件源。
2,Demo示例。(业务是发邮件)
2.1创建事件(继承java.util.EventObject)
package com.test.event;
import java.util.EventObject;
/**
* 事件类,用于封装事件源及一些与事件相关的参数.
*/
public class SendEmailEvent extends EventObject
{
private static final long serialVersionUID = -1903578788532795173L;
private Object source;//事件源
public SendEmailEvent(final Object source)
{
super(source);
this.source = source;
}
public Object getSource()
{
return source;
}
public void setSource(final Object source)
{
this.source = source;
}
}
2.2、事件监听器。实现java.util.EventListener接口,注册在事件源上,当事件源的属性或状态改变时,取得相应的监听器调用其内部的回调方法。
package com.test.event;
import java.util.EventListener;
public class SendEmailEventListener implements EventListener
{
//事件发生后的回调方法
public void fireCusEvent(final SendEmailEvent e)
{
final SendEmailEventSource sendEmailEventSource = (SendEmailEventSource) e.getSource();
System.out.println("My password has been changed!");
System.out.println("I got a new password, The password \"" + sendEmailEventSource.getPassword() + "\"");
}
}
2.3、事件源。事件发生的地方,由于事件源的某项属性或状态发生了改变(比如BUTTON被单击、TEXTBOX的值发生改变等等)导致某项事件发生。换句话说就是生成了相应的事件对象。因为事件监听器要注册在事件源上,所以事件源类中应该要有盛装监听器的容器(List,Set等等)。
package com.test.event;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 事件源
*/
public class SendEmailEventSource
{
private String password;
//监听器容器
private Set<SendEmailEventListener> listeners = null;
public SendEmailEventSource()
{
this.listeners = new HashSet<SendEmailEventListener>();
this.password = "password";
}
//给事件源注册监听器
public void addCusListener(final SendEmailEventListener cel)
{
this.listeners.add(cel);
}
public void sendEvent()
{
SendEmailEventListener cel = null;
final Iterator<SendEmailEventListener> iterator = this.listeners.iterator();
while (iterator.hasNext())
{
cel = iterator.next();
cel.fireCusEvent(new SendEmailEvent(this));
}
}
/**
* @return the password
*/
public String getPassword()
{
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(final String password)
{
this.password = password;
sendEvent();
}
}
2.4下面是主方法类(测试)
package com.test.event;
public class Test
{
public static void main(final String[] args)
{
final SendEmailEventSource sendEmailEventSource = new SendEmailEventSource();
//注册监听器
sendEmailEventSource.addCusListener(new SendEmailEventListener()
{
@Override
public void fireCusEvent(final SendEmailEvent e)
{
super.fireCusEvent(e);
}
});
//触发事件
sendEmailEventSource.setPassword("123");
}
}