具有两个观察者列表的观察者模式
我有一个 MyObserver 类,用于监听通知程序中的更改。 Notifier 扩展了 Observable 并使用 notifyObservers(Object) 通知其事件。作为参数传递的对象始终是同一类的实例。问题是每个观察者需要监听不同的事件。例如,一个观察者需要监听状态更改事件,而其他观察者则需要监听所有类型的事件。我怎样才能用观察者模式做到这一点?
谢谢。
I have a class MyObserver that listens to changes in Notifier. Notifier extends Observable and notify its events with notifyObservers(Object). The object passed as argument is always an instance of the same class. The problem is that each observer need to listen to diferent events. For example one observer needs to listen to state changed events and others to all types of events. How can I do this with observer pattern?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 notifyObservers(Object arg) 版本并创建某种“事件类型”对象来粘贴在那里。在您的观察类中,只需过滤传入的事件类。
Use notifyObservers(Object arg) version and create some sort of "event type" object to stick in there. In your observing classes simply filter on the passed in event class.
我认为观察者模式的 Java 内置实现不适合您的情况。
事实上,当只有一种 Observable 类型的事件发生时,一般的观察者模式就可以使用。在观察者设计模式中,所有观察者总是都会收到通知。
因此,在这种情况下,你需要扩展通用的观察者模式,通过定义你自己的 Observable 接口,例如,这样:
然后你可以用每种类型的内部列表来实现这个 Observable 接口要通知的事件。如果您愿意,您仍然可以使用 Java 内置的 Observer 接口。
这种方法有以下好处:
不影响代码
观察员。
事件。
真正感兴趣
每个事件。
观察者这边的技巧。
I think that the Java built-in implementation of the Observer Pattern is not suitable for your case.
In fact, the general Observer pattern is usable when just one Observable kind of events can arise. In the Observer Design Pattern, all the Observes get notified always.
So, in this case, you need to extend the general Observer pattern, by defining your own Observable interface, for example, this way:
Then you can just implement this Observable interface with internal lists for each kind of event to notify. You can still use the Java built-in Observer interface if you wish.
This approach has the following benefits:
without affecting the code of the
Observers.
event.
that are effectively interested in
each event.
tricks on the Observers side.
如果你可以稍微改变一下设计:
用法:
If you can change the design a bit:
Usage:
您可以通过在 Observable 类中执行以下操作来测试状态更改:
侦听任何内容的观察者不需要此测试。如果您只想监听状态更改,这可能是最简单的方法。
You can test for a state change by doing the following in the Observable class:
The observers that listen to anything don't need this test. This is probably the easiest way if you only want to listen for state changes.