Search code examples
design-patternsobserver-pattern

Should I use Observer or Events when just one object needs notification?


Now that I learned to use Observers two questions came to my attention:

1 - Is it common to use Observer Pattern to notify just one object about changes?
2 - When just one object need to be updated it's better to use an observer or an event? Or there are cases when just one notification is needed that Observers are more recommended?


Solution

  • I don't see Observer and Events as alternatives, it's not an or. When we set up a Subscribe/Event relationship between Event Producer and Event Consumer then we are using the Observer pattern - see Wikipedia article on Observer.

    I think your question is more on the lines of whether we really need Observer/Event when there is a very strong relationship between Producer and Consumer, a situation where we expect the Producer to know about its sole Consumer. Then instead of needing

     Define Event
     Write Subscribe Method
     Keep track of subscriptions
     Write Unsubscribe Methos
     Write Event Notification
    

    we just

     Write a dinnerIsReady(payload) method on consumer
     Arrange for producer to know about consumer (perhaps because producer creates consumer)
     consumer.dinnerIsReady(payload)
    

    Which is somewhat less work. [Perhaps it's not much less work in those environments that have nice event Frameworks.]

    The Observer Pattern is pretty much essential if you have several consumers. When initially you have just one consumer it may well be overkill to go for the full Subscribe/Publish model. If instead you just use an Payload/ConsumerInterface model you get decoupling of Producer and Consumer with less work.

     Consumer implements IDinnerIsReady
    
     Publisher.registerConsumer(IDinnerIsReady c)
     {
          assert(no existing consumer);
          myConsumer = c;
     }
    
     ...
         c.dinnerIsready();
     ...
    

    I would see this as entirely reasonable.