码迷,mamicode.com
首页 > 编程语言 > 详细

java监听器示例

时间:2015-07-01 18:18:41      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:java   监听器   观察者模式   

监听器的原理是观察者模式。就像明星(事件源)聚拢了一群粉丝(观察者)。当明星有啥举动的时候会通过粉丝们报道出去。订阅信息、计算器按钮都是该原理的应用。

下面写了一个监听器的小例子:


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();
}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

java监听器示例

标签:java   监听器   观察者模式   

原文地址:http://blog.csdn.net/keketrtr/article/details/46711961

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!