简体   繁体   中英

CLS parameter in Singletons

I'm doing an exercise in Java on Singletons and I have to use the cls parameter in order to complete it. I'm very new to Java and haven't come across this yet.

public class Speakerphone extends Object{
public void shoutMessage()

I have to do the following to complete the code. How do I utilize the cls parameter to finish this off?

  1. shoutMessage
  2. Sends the message to all of the Listeners which are instances of the cls parameter

@param talker a Talker whose message will be sent (Talker)

@param cls a Class object representing the type which the Listener should extend from in order to receive the message (Class)

@return nothing

Something like this?

Talker:

public interface Talker<T> {

    public T getMessage();
}

Listener:

public interface Listener<T> {

    public void receive(T message);
}

Speakerphone:

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);
        }
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM