定义一个事件类
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Event {
private Object object;
private String methodName;
private Object[] params;
private Class[] paramTypes;
public Event(Object object, String methodName, Object... params) {
this.object = object;
this.methodName = methodName;
this.params = params;
initParamTypes(params);
}
private void initParamTypes(Object[] params) {
this.paramTypes = new Class[params.length];
for (int i = 0; i < params.length; i++) {
this.paramTypes[i] = params[i].getClass();
}
}
public void invoke() {
try {
Method method = object.getClass().getMethod(this.methodName, this.paramTypes);
if (method == null) {
return;
}
method.invoke(this.object, this.params);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
管理事件的类
import java.util.ArrayList;
import java.util.List;
public class EventHandler {
private List<Event> events;
public EventHandler() {
events = new ArrayList<Event>();
}
public void addEvent(Object object, String methodName, Object... params) {
events.add(new Event(object, methodName, params));
}
public void Notify() {
for (Event event : events) {
event.invoke();
}
}
}
抽象通知
public abstract class Notifier {
private EventHandler eventHandler = new EventHandler();
public abstract void addListener(Object object, String methodName, Object... params);
public abstract void Notify();
public EventHandler getEventHandler() {
return eventHandler;
}
public void setEventHandler(EventHandler eventHandler) {
this.eventHandler = eventHandler;
}
}
具体通知
public class ConcreteNotifier extends Notifier {
@Override
public void addListener(Object object, String methodName, Object... params) {
this.getEventHandler().addEvent(object, methodName, params);
}
@Override
public void Notify() {
this.getEventHandler().Notify();
}
}
监听
public class WatchingTVListener {
public WatchingTVListener() {
System.out.println("WATCHING TV");
}
public void stopWatchingTV(String string) {
System.out.println("STOP WATCHING " + string);
}
}
测试
public class Main {
public static void main(String[] args) {
Notifier notifier = new ConcreteNotifier();
WatchingTVListener listener = new WatchingTVListener();
notifier.addListener(listener, "stopWatchingTV", "方法参数");
notifier.Notify();
}
}