DEV Community

Cover image for Observer Pattern
Francesco Ciulla
Francesco Ciulla

Posted on • Updated on

Observer Pattern

Subscribe to object changes

GitHub: https://github.com/FrancescoXX/Design-Patterns-Observer-Javascript
CodePen: https://codepen.io/francescoxx/pen/NWqvPrb

The Observer Design pattern, is a very simple yet powerful pattern.

We can use it when we want, for example, to update a UI when an object of our application changes its state.

So we have:

  • a SUBJECT: the Thing we want to observe
  • a set of OBSERVERS, which are updated when the subjects changes its state

When the subject changes its state, it notifies, to all subscribed observable, that he changed its state, and all the observers added to the subject gets updated,

That is pretty much how it works when someone updates its twitter with a new tweet! all its followers get updated with a notification


Alt Text

Problem

When data changes, we want the UI to reflect the new state


Intent

  • Define a one-to-many dependency between objects
  • When one object changes state, all its dependents are notified and updated automatically.

Applicability

  • Use : Change one object -> change others
  • No idea how many objects need to be changed
  • Object change notification, with preserving loose coupling
  • One object may notify another without knowing them directly

Benefits

  • Loose coupling between observers and subjects
  • Supporting a broadcast model

Drawbacks

  • One change can result in multiple unnecessary notifications
  • Clients don't know the ripple effects

Conclusion: Observer pattern is great to

  • Preserve loose coupling
  • Observe state in other objects, then notify when state changes

Now lets take a look at the Structure of this pattern when we want to implement it

Alt Text

And lets take a look at the Collaboration among them

Alt Text

That’s it!
This pattern is very simple and it could be useful when we want to observe the same thing from different points of our application!

GitHub: https://github.com/FrancescoXX/Design-Patterns-Observer-Javascript
CodePen: https://codepen.io/francescoxx/pen/NWqvPrb

Top comments (0)