Search code examples
javaswinggenericsobserver-pattern

Java - How to avoid overriding addObserver Observable everytime?


I am currently working on a small game for University. I have a model that extends Observable and implements a Interface.

Due the interface I have to override the addObserver method everytime for every Observer I add. And add the additonal method to the interface. By now it looks like this:

@Override
public void addObserver(UniversityView universityView) {
    super.addObserver(universityView);

}
@Override
public void addObserver(CourseView courseView) {
    super.addObserver(courseView);

}
@Override
public void addObserver(TaskForceView taskForceView) {
    super.addObserver( taskForceView);
}

In which every view is a extended JPanel. Since I am bound to specific metrics which also include the maximum amount of method per class, I like to reduce it to one. Or to avoid overriding the addObserver method at all. Since I am using the parent Method any way.

But here is the problem: I don't really know how. There is only one solution I could think of that would be to use generics. But I am not too familiar with generics.

Thanks for any help!


Solution

  • If your views all extend JPanel, you could just do this

    @Override
    public void addObserver(JPanel someView) {
        super.addObserver((Observer) someView);
    }
    

    Just an idea about avoiding it altogether would be to register your views as observers when you create them. Would look something like this:

    public class TaskForceView extends JPanel implements Observer{
         public TaskForceView(Observable observable){
             ...  
             observable.addObserver(this);
         }
    }
    

    (I didn't try this out and it somehow works against the observer pattern, as it inverts the way it is usually used)