addEventListener()、removeEventListener()实现机制
UML图
OnListener接口
1 public interface OnListener {
2 void handleMessage(Event evt);
3 }
IEventDispatcher接口
1 public interface IEventDispatcher {
2 void addEventListener(String type, OnListener listener);
3 void removeListener(String type, OnListener listener);
4 void dispatchEvent(Event event);
5 void Notify();
6 }
Event事件类
1 public class Event{
2 public static String FINISH = "finish";
3 public String type;
4 public Event(String evt) {
5 this.type = evt;
6 }
7 public String getEvent() {
8 return type;
9 }
10 }
EventDispatcher事件处理
1 import java.util.ArrayList;
2 import java.util.HashMap;
3 import java.util.List;
4
5 public class EventDispatcher implements IEventDispatcher {
6 private static Event evt;
7 private static List<HashMap<String, OnListener>> onList = new ArrayList<HashMap<String, OnListener>>();
8
9 @Override
10 public void addEventListener(String type, OnListener listener) {
11 HashMap<String, OnListener> map = new HashMap<String, OnListener>();
12 map.put(type, listener);
13 onList.add(map);
14 }
15
16 @Override
17 public void removeListener(String type, OnListener listener) {
18 HashMap<String, OnListener> map = new HashMap<String, OnListener>();
19 map.put(type, listener);
20 onList.remove(map);
21 }
22
23 @Override
24 public void dispatchEvent(Event event) {
25 evt = event;
26 Notify();
27 }
28
29 @Override
30 public void Notify() {
31 for (int i=0; i<onList.size(); i++){
32 if (onList.get(i).containsKey(evt.getEvent())){
33 onList.get(i).get(evt.getEvent()).handleMessage(evt);
34 }
35 }
36 }
37 }
//使用
Execution类(系统负责接收消息,调用分发事件)
1 public class Execution extends EventDispatcher{
2 public Execution(){
3 }
4
5 public void doAction(){
6 this.dispatchEvent(new Event(Event.FINISH));
7 }
8
9 public static void main(String[] args){
10 new Register();
11 new Execution().doAction();
12 }
13 }
Register类由用户注册事件、实现事件执行
1 public class Register extends EventDispatcher implements OnListener {
2
3 public Register(){
4 //注册事件监听器
5 this.addEventListener(Event.FINISH, this);
6 }
7
8 @Override
9 public void handleMessage(Event evt) {
10 System.out.println("事件"+evt.getEvent());
11 }
12
13 }
类似观察者模式
观察者将自己注册到被观察者的容器中,然后在本地接收事件。被观察者不负责直接调用和发送消息,由FLASH或JAVA系统虚拟机接收系统事件,判断注册事件是否发生,然后由虚拟机事件系统管理发送事件消息(dispatchEvent())。