观察者模式的反面是什么?
据我了解,观察者模式允许多个观察者监视单个主题。相反的情况是否有模式?是否有一种模式可以让单个观察者监视多个主题并在其中任何一个主题引发(例如,Notify 事件)时做出响应?
As I understand it, the observer pattern allows for multiple observers to monitor a single subject. Is there a pattern for the opposite scenario? Is there a pattern for a single observer that monitors several subjects and responds when any one of them raises, say, a Notify event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。它只是观察者模式的另一个应用。
观察者将自己添加到许多主题中。
如果您希望无论您正在观察哪个主题都执行相同的操作,那么这与您正在使用的观察者模式完全相同。
如果您想要根据哪个主题触发事件而执行单独的操作,那么您可以使用传递到观察者的 ActionPerformed 方法中的 Action 参数来帮助确定哪个主题触发了事件。 (这些名称可能会根据您选择的语言或库而变化)
Yes. It is just another application of the observer pattern.
The Observer adds itself to many Subjects.
If you want the same action to be performed no matter Which subject you're observing then this is exactly the same as the Observer pattern you are using.
If you want a separate action depending on which Subject triggered the event then you can use the Action parameter that is passed into the Observer's ActionPerformed method to help determine which subject triggered the event. (these names may change depending on your language or library of choice)
还要考虑相关的中介模式。
更多信息请参见: http://sourcemaking.com/design_patterns/mediator
我也非常喜欢@CDC关于中介者与观察者面向对象的设计模式:
Also consider related Mediator pattern.
More info here: http://sourcemaking.com/design_patterns/mediator
I also very like @CDC's answer on Mediator Vs Observer Object-Oriented Design Patterns:
如果您只希望观察者做出反应一次,无论有多少受监视对象引发事件,那么一旦第一个源触发事件,您就必须让事件处理程序的一部分从所有其他源“取消注册”观察者,或者您必须决定应该使用多长时间或什么时间标准来决定来自另一个事件(或在某个定义的时间间隔后再次来自同一源)的事件何时应导致观察者再次做出反应......
if you only want the observer to react once, no matter how many monitored objects raise the event, then you will have to have part of the event handler "unregister" the observer from all other sources once the first source fires the event, or you will have to decide how often or what timing criteria should be used to decide when an event from another (or the same source again after some defined interval) should cause the observer to react again...
如果观察者监视的对象相似,那么你可以让观察者监视所有对象,如果不是,我认为你最好将监视者分开,然后你将遵循单一职责规则。
If the subjects the observer monitor are similar, then you can make the observer monitor them all, if not, i think you'd better seperate the montior, then you'll follow the single responsibility rule.
观察者模式仍然可以使用:只需将相同的对象注册为许多受监视对象的观察者即可。您可能希望“通知”事件接收某种被观察对象标识符(“this”指针、唯一的 ID 号等),以便观察者对象可以选择适合报告事件的对象的操作。
The Observer pattern can still be used: just have the same object register as an observer to many monitored objects. You'll probably want the "Notify" event to receive some kind of observed-object identifier (the "this" pointer, a unique id number etc) so that the observer object can choose an action appropriate to the object reporting the event.