用Notifier类实现Event/Listener更容易

Event/Listener模式在Java中很常见,并且很有用,但要自己来实现这个模式是一件很费时间并且单调乏味的工作。每次你都不得不和List或Vector打交道,每次你都不得不处理Add方法、Remove方法,然后你还得遍历整个列表来通知所有的监听者,这才算完。 如果能象下面这样简单就好了: Notifier notifier = new Notifier("actionPerformed"); ... notifier.addListener( someObject ); ... notifier.notify( new ActionEvent(this) ); 只要几行代码就能够完成一切。 下面的Notifier类就达到了这个目的: package com.generationjava.lang; import java.util.*; import java.lang.reflect.*; public class Notifier { private ArrayList listeners = new ArrayList(); private String listenerMethod; public Notifier(String name) { this.listenerMethod = name; } public void addListener(Object not) { this.listeners.add(not); } public void removeListener(Object not) { this.listeners.remove(not); } public void notify(EventObject event) { Iterator itr = listeners.iterator(); while(itr.hasNext()) { try { Object listener = itr.next(); Class clss = listener.getClass(); Method method = clss.getMethod( this.listenerMethod, new Class[] { event.getClass() } ); method.invoke( listener, new Object[] { event } ); } catch(Exception e) { e.printStackTrace(); } } } } 这个类并没有经过性能上的优化,而且它是不同步的,但在编写一组Event/Listener API的时候,可以很快掌握它并且节省时间。利用Notifier类,你就能执行这样一个常见的任务而不必每次都为之编写代码。 <淘宝热门商品:
 

132.00 元 

假一罚十 专柜正品 进口牛皮单肩包

 

100.00 元 

韩国手表正品intercrew品牌手表LED手表


来源:程序员网

小小豆叮

0 Responses to "用Notifier类实现Event/Listener更容易"

发表评论