0

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

John L
  • 11
  • 2
  • So, you need to add 2 parameters to the shoutMessage() method. One must be of type Talker, and the second must be of type Class. How about starting to do that? If you don't know what method parameters are, then you shouldn't deal with singletons and listeners yet. Start with basic stuff. – JB Nizet Jul 21 '15 at 18:13

1 Answers1

0

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);
        }
    }    
}
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37