我更喜欢使用注释,以便侦听器可以侦听不同类型的事件。
public class BrokerTestMain {
public static void main(String... args) {
Broker broker = new Broker();
broker.add(new Component());
broker.publish("Hello");
broker.publish(new Date());
broker.publish(3.1415);
}
}
class Component {
@Subscription
public void onString(String s) {
System.out.println("String - " + s);
}
@Subscription
public void onDate(Date d) {
System.out.println("Date - " + d);
}
@Subscription
public void onDouble(Double d) {
System.out.println("Double - " + d);
}
}
指纹
String - Hello
Date - Tue Nov 13 15:01:09 GMT 2012
Double - 3.1415
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Subscription {
}
public class Broker {
private final Map<Class, List<SubscriberInfo>> map = new LinkedHashMap<Class, List<SubscriberInfo>>();
public void add(Object o) {
for (Method method : o.getClass().getMethods()) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (method.getAnnotation(Subscription.class) == null || parameterTypes.length != 1) continue;
Class subscribeTo = parameterTypes[0];
List<SubscriberInfo> subscriberInfos = map.get(subscribeTo);
if (subscriberInfos == null)
map.put(subscribeTo, subscriberInfos = new ArrayList<SubscriberInfo>());
subscriberInfos.add(new SubscriberInfo(method, o));
}
}
public void remove(Object o) {
for (List<SubscriberInfo> subscriberInfos : map.values()) {
for (int i = subscriberInfos.size() - 1; i >= 0; i--)
if (subscriberInfos.get(i).object == o)
subscriberInfos.remove(i);
}
}
public int publish(Object o) {
List<SubscriberInfo> subscriberInfos = map.get(o.getClass());
if (subscriberInfos == null) return 0;
int count = 0;
for (SubscriberInfo subscriberInfo : subscriberInfos) {
subscriberInfo.invoke(o);
count++;
}
return count;
}
static class SubscriberInfo {
final Method method;
final Object object;
SubscriberInfo(Method method, Object object) {
this.method = method;
this.object = object;
}
void invoke(Object o) {
try {
method.invoke(object, o);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
}