1

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!

c-pid
  • 122
  • 1
  • 9
  • Some alternative implementations of the observer pattern are mentioned [here](http://stackoverflow.com/a/3072979/230513). – trashgod Jun 02 '14 at 18:53

1 Answers1

3

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)

Dave
  • 1,784
  • 2
  • 23
  • 35
  • 1
    Hey this was way to simple for me to even think about it. The only thing that I had to do in your solution was to cast someView to Observer. Something like super.addObserver((Observer) panel); I don't want to mark your answer as the solution tho since I am also intrested if there is a way how to avoid this method at all. Many thanks! – c-pid Jun 02 '14 at 18:37
  • Indeed, one needs to cast to Observer, went past me. I guess I started relying on my IDE yelling at me. – Dave Jun 02 '14 at 18:38
  • Added another possiblity. – Dave Jun 02 '14 at 19:02