JAVA : 简单event机制的实现(伪码)

<S> 
public interface EventBase<S> {
void onEvent(S source, Object[]... arguments);
}
<S,T extends EventBase<S>>
public class EventSender<S, T> {
private List<T> receivers = new ArrayList<T>();
public void addReceiver(T receiver) {
if (null == receiver) 
throw new RuntimeException("Can't add null as receiver");
this.receivers.add(T);
}
public void removeReceiver(T receiver) {
if(this.receivers.contains(receiver)) {
this.receivers.remove(receiver);
}
}
public void triggerEvent(S source, Object[]... arguments) {
for(T receiver : this.receivers) {
receiver.onEvent(source, arguments);
}
}
}
//declare the event 
<S>
public interface OnLoadEvent<S> extends EventBase<S {
}
//test class
public MyEntityObj {
//use the event in the class
public EventSender<MyEntityObj, OnLoadEvent<MyEntityObj>> onLoad() {
return onLoadEvent;
}
private EventSender<MyEntityObj, OnLoadEvent<MyEntityObj>> onLoadEvent = new ....;
private void someMethod() {
//do something
this.onLoad().triggerEvent(this, "This is a test", 100);
}
}
//receiver class
public class SimpleReceiver {
MyEntityObj obj;
class myOnLoadHandler implements OnLoadEvent<SimpleReceiver> {
void onEvent(S source, Object[]... arguments){
//print something here when receive the event
}
}
public void init() {
//register event
obj.onLoad().addReceiver(new myOnLoadHandler());
}
}

posted on 2012-03-22 00:52  learner  阅读(579)  评论(0编辑  收藏  举报

导航