djcredo
djcredo

Reputation: 1187

Pulling the observer pattern out into a Service

I am a big fan of the Observer pattern. In our code we use it in many places to decouple services from each other. However, I've seen it implemented poorly in many places since there is a lot to worry about:

What's more, we end up repeating this code all over the place. In the spirit of DRY, I want to pull out all Notification concerns into a single service. Some pseudo code:

Interface NotificationService
   // register the listener to receive notifications from this producer
   registerAsListener (NotificationProducer, NotificationListener)

   // Sends a notification to listeners of this producer
   sendNotification (NotificationProducer, Notification)

   // Sends a notification in a background thread
   sendAsynchNotification (NotificationProducer, Notification)

   // Listener no longer receives messages from this producer
   removeListener(NotificationProducer, NotificationListener)

My question is this: am I losing the original point of the observer pattern by doing this? Am I making a mistake by introducing another dependency on both sides of the pattern? Both the Listener and the Producer will now have an extra dependency on NotificationService.

What are your views?

Upvotes: 1

Views: 294

Answers (1)

LiorH
LiorH

Reputation: 18824

you are right with your concerns and questions. implementing the observer pattern many times seems like plain repetition. you're also right that the above solution does lose the pattern's objective.

what you've just implemented is a (global?) event bus. it's a matrix of producers and listeners. that's useful for many applications (see GWT's event bus ).

however if you just want to minimize code duplication while maintaining the pattern. you can remove the coupling between the listeners and the service, use a minified version of the above interface as a member of the observed class. so the logic of registration and notification is written once. the observed class is just delegating the registration and notification logic to the service.

class ObservedClass implements Observable {
    NotificationService notificationService = new NotificationServiceImpl (this);
    ....
 }

interface NotificationService {
   // register the listener to receive notifications from this producer
   registerAsListener ( NotificationListener)

   // Sends a notification to listeners of this producer
   sendNotification (Notification)

   // Sends a notification in a background thread
   sendAsynchNotification (Notification)

  // Listener no longer receives messages from this producer
  removeListener(NotificationListener)

Upvotes: 1

Related Questions