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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值