I tried to use the observer pattern in a relatively simple application.
I have 4 classes of GUI
- StarterClass (contains
CompositeWordLists
and CompositeWordListData
) - CompositeWordLists (contains a lot of
CompositeListItem
/ s and a CompositeWordListData
) - CompositeWordListData strong> (contains
DialogWordData
) - DialogWordData STRONG>
Here is my observed
interface Observable<T> { void addObserver(T o); void removeObserver(T o); void removeAllObservers(); void notifyObservers(); }
And I create Observers as follows:
public class Observers { private Observers(){}; interface WordListsObserver { public void update(CompositeWordLists o); } interface ListItemObserver { public void update(CompositeListItem o); } }
Basically, I have problems indicating the type of event that occurred. For example, the CompositeWordLists
class needs to know when the CompositeListItem
deleted, saved, edited, etc., but I only have one update method ... my brain hurts!
What is the best way to do this?
UPDATE
I'm having problems with this, I added events and changed Observable and Observers, but now I have type security issues.
public class Observers { private Observers(){}; interface ObservableEvent<T> { T getEventObject(); } interface ObserverAuthenticationAttempt { public void update(ObservableEvent<Boolean> e); } interface ObserverWordDeleted { public void update(ObservableEvent<Integer> e); } }
The Observable interface now looks like this
interface Observable<T> { void addObserver(T o); void removeObserver(T o); void removeAllObservers(); <K> void notifyObservers(Observers.ObservableEvent<K> e); }
The problem is that when I implement this, I get and will have to distinguish K from the corresponding type, and not from what I want to do.
@Override public <K> void notifyObservers(ObservableEvent<K> e) { for(Observers.ObserverAuthenticationAttempt o : this.observers) o.update(e); }
What am I doing wrong?
update 2
It actually works better with Observable, but I still need to specify the correct EventType in two different places.
interface Observable<T,K> { void addObserver(T o); void removeObserver(T o); void removeAllObservers(); void notifyObservers(Observers.ObservableEvent<K> e); }