What is the opposite of the observer pattern?
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?
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.
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.
精彩评论