I have 3 classes: a transmitter, a view for displaying and a recording view for flushing the screen contents into a file. The view and the recording view classes register themselves from their constructor in the transmitter, which keeps them in a HashMap. The transmitter implements all the view and recording view classes' interfaces, and delegates the incoming method invocations to them based on the actually registered implementors.
To make things clear:
public interface IRecordingView {
public void recordingViewMethod1();
public void recordingViewMethod2();
}
public class RecordingView implements IRecordingView {
public RecordingView {
Transmitter.getInstance().register(this);
}
@Override public void recordingViewMethod1() { ... }
@Override public void recordingViewMethod2() { ... }
}
public interface IView {
public void viewMethod1();
public void viewMethod2();
}
public class View implements IView {
public View() {
Transmitter.getInstance().register(this);
}
@Override public void viewMethod1() { ... }
@Override public void viewMethod2() { ... }
}
public class Transmitter implements IRecordingView, IView {
private static final Transmitter instance = new Transmitter();
private HashMap<Class, Set> register = new HashMap<Class, Set>();
public Transmitter() {
for (Class cl : this.getClass().getInterfaces()) {
register.put(cl, new HashSet());
}
}
public void register(Object listener) {
for (Class interf : register.keySet()) {
if (interf.isInstance(listener)) {
Set implementors = register.get(interf);
implementors.add(listener);
}
}
}
@Override public void viewMethod1() {
for (IView delegate : register.get(IView.class)) {
delegate.viewMethod1();
}
}
@Override public void recordingViewMethod1() {
for (IRecordingView delegate : register.get(IRecordingView.class)) {
delegate.recordingViewMethod1();
}
}
// and so on for the rest of the methods
}
This is the basic concept of the legacy code. Of course there are many transmitters, each implementing more interfaces, with each interface having more methods. Is there an optimal and/or elegant way to further reduce code size? The delegation mechanism looks quite the same in every method, but I don't want to mess with reflection.