我正在做一个关于单例的Java练习,我必须使用cls参数才能完成它。我对Java很陌生,还没有遇到过这个。
public class Speakerphone extends Object{
public void shoutMessage()
我必须做以下的事情来完成代码。我如何利用cls参数来完成这个任务?
- shoutMessage
- 将消息发送给所有的listener,这些listener是参数
@param talker将要发送消息的talker (talker)
@param类对象表示侦听器的类型为了接收消息(Class)
,应该扩展from@return没有
像这样?
说话:
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);
}
}
}