像这样的东西?
说话者:
public interface Talker<T> {
public T getMessage();
}
听众:
public interface Listener<T> {
public void receive(T message);
}
免提电话:
public final class Speakerphone {
public static final Speakerphone INSTANCE = new Speakerphone();
private Map<Class, List<Listener>> listenersByTypes = new HashMap<>();
private Speakerphone() {
}
public <T> void register(Listener<T> listener, Class<T> c){
List<Listener> listeners = listenersByTypes.get(c);
if (listeners == null){
listeners = new ArrayList<>();
listenersByTypes.put(c, listeners);
}
listeners.add(listener);
}
public <T> void unregister(Listener<T> listener, Class<T> c){
List<Listener> listeners = listenersByTypes.get(c);
if (listeners != null){
listeners.remove(listener);
}
}
public <T> void shoutMessage(Talker<T> talker, Class<T> c) {
T message = talker.getMessage();
List<Listener> listeners = this.listenersByTypes.get(c);
for (Listener<T> listener : listeners) {
listener.receive(message);
}
}
}