Observer pattern using Typescript

Ramesh Kumar
2 min readJun 12, 2021

Recently I got hooked with the typescript. I wanted to learn more about it, so the best way I thought would be to implement few design patterns using typescript.

Before we jump into code, let’s first try to understand the observer pattern. What observer mean in general.

  • Observer — an entity who watches or noticed something happen to the subject.
    - An observer should update when somethings changes in subject
  • Subject/Observable — the entity on which Observer is interested.
    - Subject should able to register/subscribe a observer
    - Subject should able to de-register/unsubscribe observer
    - Subject should able to notify all the subscribed observers about changes.

To implement the observer pattern we need to first implement these two definitions. Let’s try to create two public interface in-order to achieve that.

The below one is simple observer interface which would have just one method update. And it accepts the subject as param. Any one who wanted to observe the subject should implement this interface.

The below interface define the Subject/ Observable responsibility. Every subject which we wanted to be observed should implement this interface.

Now we have our two basic interface definition done, we can go on implementing a proper example of observable pattern. Let assume we have a score application. The score application responsibility to always update the score and get the latest score. In order to view this score we have two application dashboard and cli which are interested in the latest score. So the idea is whenever we update the score these application should also notified to update to latest score. So here our score application is Subject/Observable and our application dashboard and cli are Observers.

Let’s first build of base subject class, so any class who wanted to be Observable can be easily extend it and can have default behaviour of Observable.

Cool now our base class is ready, let’s try to implement Score class, as mentioned earlier there are only two responsibility of score class, to update score and to get latest score. Once we update score we notify our observers for the new update.

Let’s now implement our other two application classes which are interested in the latest score. Since they both observing the Score class they should implement Observer interface.

Now these above classes just need to subscribe to Score class and done. Whenever a score updated, it will notify all subscribed observers.

I hope this would help someone to understand how observer pattern works and can be easily implemented in typescript. Putting it all together

--

--

Ramesh Kumar

Backend Developer , always eager to learn and share knowledge