Tuesday, 21 November 2017

Design Patterns - Observer

The observer design pattern is useful in cases we want a change in an object (subject) to be known to one or more other objects (observers).
This design pattern is allowing us to avoid coupling and it's pitfalls in a clean , easy to scale way.

The observer pattern is comprised of two elements:
  1. Registration: Here the subject is adding the observer/list of observers (method is provided by the subject class) the method typically is called register , addObserver etc...
  2. Notification: After the desirable event happened the subject is updating the observers that have been registered by calling an update method (provided by the observer class) to perform the desirable action.

To implement the pattern two classes are needed: the subject and the observer , below you can see the relationship in a UML diagram :

A subject class has a list of observers , by calling the addObservers method we add more observers
and when something interesting happens in the subject we call the notifyObservers which loops through our observer list calling each observers update method.

We can illustrate this behavior by a simple example :
    We have a Blog and Subscribers , when the Blog publishes a new Article the Subscribers want to be updated about the article. In this example the Blog is the subject and Subscribers are the observers.
    Take a look at the following diagram illustrating how we could make it happen:

The Subject is a regular class and the Observer is an interface : the addObserver it will be called when the Blog is calling it's subscribe method , the notifyObserver would be called when publishArticle is called because that's the method that does something our observers are interested about.

The point is to have an action in the subject to update our observers.
You need to know :
  • When to add observers in the subject list
  • What is the action in the subject that interests your observers?
  •  What the observer is supposed to do when it's update method is called ?
Plan carefully what you will do , before you do it.

Get the example code on github

Happy coding !!!

No comments:

Post a Comment