I have the following:
A Java class: ClassA implements Observer
A Java Interface: Inter (extends Observable, not possible)
A Java class: ClassB implements Inter extends Observable
A Java class: ClassC implements Inter extends Observable
Now the code for ClassA is somewhat like this.
ClassA{
Inter anyClass = new ClassB();
//or it could be
Inter anyClass = new ClassC();
//Inter.addObserver(this); //not possible since Interface cannot extend Observable
}
Now if a particular event happens in ClassB or ClassC, I want ClassA to know about it. I thought of using the Observer/Observable but the problem is that the Interface cannot extend Observable.
If someone understands the question please help me find a way to update ClassA when something happens in ClassB or ClassC.
By the 3 and 4 conditions I assume that Observable is a class, because ClassB and ClassC are extending it. So, why don't you put the addObserver method in Observable class? Then you could assign ClassB or ClassC instances to an Observable anyClass variable, and register the observer via addObserverMethod:
You don't specifically have to use the built-in Observer/Observable java implementation. You can create your own interfaces to use the observer pattern.
Create an interface Observer with the method 'update' or 'notify' (or something like that) which will be used for ClassA
then to use the 'Inter' interface to act as an Observable make sure it implements the following:
Make sure classes that implement the 'Inter' interface also have an arraylist called observerCollection to keep track of the observers. Then everytime something changes in ClassB or ClassC and you want to tell ClassA (the observer) you can call notifyObservers() to let it know something has changed.
Take a look at this to see what happens with the observer design pattern: http://en.wikipedia.org/wiki/File:Observer.svg
Simply define your own interface IObservable with the appropriates methods addObserver and deleteObserver:
Your interface can extend this IObservable interface:
In your class A and B, the addObserver and deleteObserver methods will be inherited from the Observable class and do not need to be defined.