What is the opposite of the observer pattern?

青春壹個敷衍的年華 提交于 2019-11-27 20:38:53

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.

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)

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.

Petr Cibulka

Also consider related Mediator pattern.

Mediator pattern defines an object that encapsulates how a set of objects interact (Wikipedia)

More info here: http://sourcemaking.com/design_patterns/mediator

I also very like @CDC's answer on Mediator Vs Observer Object-Oriented Design Patterns:

The Observer pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

The Mediator pattern: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!