监听器的原理是观察者模式。就像明星(事件源)聚拢了一群粉丝(观察者)。当明星有啥举动的时候会通过粉丝们报道出去。订阅信息、计算器按钮都是该原理的应用。
下面写了一个监听器的小例子:
package listener;
import java.util.EventObject;
/**
* 定义事件对象,用于标记当前进行的动作。必须继承EventObject。
* @author zyj
*
*/
public class StateEvent extends EventObject {
private static final long serialVersionUID = 5323292975415079206L;
private Enum<ActionEnum> action;
public StateEvent(Object source, Enum<ActionEnum> action) {
super(source);
this.action = action;
}
public Enum<ActionEnum> getAction() {
return action;
}
public void setAction(Enum<ActionEnum> action) {
this.action = action;
}
}
package listener;
public enum ActionEnum {
wake,sleep;
}
package listener;
import java.util.EventListener;
/**
* 定义监听接口,负责监听StateEvent事件。必须继承EventListener。
* @author zyj
*
*/
public interface StateListener extends EventListener {
void handleState(StateEvent event);
}
package listener;
public class WakeListener implements StateListener {
@Override
public void handleState(StateEvent event) {
if(event.getAction() != null && event.getAction().equals(ActionEnum.wake)){
System.out.println("你醒了!");
}
}
}
package listener;
public class SleepListener implements StateListener {
@Override
public void handleState(StateEvent event) {
if(event.getAction() != null && event.getAction().equals(ActionEnum.sleep)){
System.out.println("你睡了!");
}
}
}
package listener;
import java.util.ArrayList;
import java.util.List;
public class StateManager {
private List<StateListener> list = new ArrayList<StateListener>();
public boolean addListener(StateListener listener){
if(listener == null)
return false;
return list.add(listener);
}
public boolean removeListener(StateListener listener){
if(listener == null)
return false;
return list.remove(listener);
}
private void notifyAllListeners(StateEvent event){
for(StateListener listener : list){
listener.handleState(event);
}
}
public void wake(){
StateEvent event = new StateEvent(this, ActionEnum.wake);
notifyAllListeners(event);
}
public void sleep(){
StateEvent event = new StateEvent(this, ActionEnum.sleep);
notifyAllListeners(event);
}
}
package listener;
public class ListenerTest {
public static void main(String[] args) {
StateManager manager = new StateManager();
manager.addListener(new WakeListener());
manager.addListener(new SleepListener());
manager.wake();
System.out.println("-----------------");
manager.sleep();
}
}