对彼此不直接了解的对象使用观察者模式
这是我的 Observer 和 Observable 接口,
public interface Observable<T> {
void addObserver(Observer<T> o);
void removeObserver(Observer<T> o);
void removeAllObservers();
void notifyObservers();
}
public interface Observer<T> {
public void update(Observable<T> o);
}
如果我有两个相互了解的类,这些接口就可以工作,但是,我该如何处理如下情况。
- RootComposite(创建单词列表)
- WordListComposite(创建单词)
- WordDialog
现在,如果 RootCompoiste 需要了解 WordListComposite 中的更改,我可以按如下方式实现它:
public class RootComposite extends Composite implements Observer<WordListComposite > {
public RootComposite() {
WordListComposite wl = new WordListComposite();
wl.addObserver(this);
}
...
@Override
public void update(WordListComposite o) {
this.lblMessage = o.getMessage();
}
...
}
这将按预期工作。
但是 RootComposite 如何接收来自 WordDialog 的更新呢?
在这种情况下最好的方法是什么?
Here are my Observer and Observable interfaces
public interface Observable<T> {
void addObserver(Observer<T> o);
void removeObserver(Observer<T> o);
void removeAllObservers();
void notifyObservers();
}
public interface Observer<T> {
public void update(Observable<T> o);
}
These work if I have two classes that know about each other, however, how do I handle a situation like below.
- RootComposite (Creates a Word List)
- WordListComposite (Creates a Word)
- WordDialog
Now if RootCompoiste needs to know about changes in WordListComposite, I can implement it like that following:
public class RootComposite extends Composite implements Observer<WordListComposite > {
public RootComposite() {
WordListComposite wl = new WordListComposite();
wl.addObserver(this);
}
...
@Override
public void update(WordListComposite o) {
this.lblMessage = o.getMessage();
}
...
}
This will work as expected.
But how does RootComposite receive updates from WordDialog?
What is the best approach in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WordListComposite 还可以实现 Observer 接口,而 WordDialog 则实现 Observable 接口。 WordListComposite 可以观察 WordDialog,当它收到来自 WordDialog 的通知时,会触发向 RootComposite(正在观看 WordListComposite)的通知。基本上,您有一个动作触发,然后只需将通知发送到树上即可。
WordListComposite could also implement the Observer interface and WordDialog the Observable interface. WordListComposite could observe WordDialog and when it receives a notification from WordDialog trigger a notification to RootComposite (who is watching WordListComposite). Basically you have an action fire, and then just send the notifications up the tree.