JavaScript – Observer Pattern

GitHub Code

Pattern three in this series will be the observer pattern.

I spent sometime reading up on this pattern because initially, I thought it would be similar to the visitor where instead of a group of classes being ‘visited’ by an object, they would be ‘assigned’ an observer and it would report on the internal state of the object being ‘observed’.  In the previous visitor post, I created one visitor the ‘visited’ each system that was created.  The ‘process’ was the system would accept the visitor via a method and inside that system method, the visitor passed a reference to itself of the system being ‘visited’.

With this access, the visitor could report on anything inside the system. The duel reference (i.e. system had to get a reference to the visitor and then passed a reference of itself back to the visitor) is a little confusing to me.  I see why it is necessary, but I would think that adding a reference to the system being visited would be enough.  Anyways, I was expecting a similar set up with the observer pattern.  I was a little surprised though 🙂

It most of the examples I reviewed, there was only one object under observation by multiple observers.  The use of interfaces vs abstract classes also seemed ambiguous (i.e. both are used).  The ‘key’ is that there is one ‘subject’ and multiple observers that report on this single subject.  There was also the duel reference issue again.  In a future post (assuming I can remember 🙂 ), I am going to explore whether this duel reference is actually needed.  It seems like it should not be.

For this sample, I opted to just create one system and three observers with no interfaces and/or abstract classes.  To run:

  • Download and run the project


  • Review output


The program structure consists of one JavaScript file which:

  • Consists of a run method


  • System


  • Three observers


In use:

  • One system is created
  • Three observers are created and given a reference to the system
  • The system has each observer added to its observer list

The system calls ‘notifyObservers()’ when a change occurs and each observer than ‘reports’ on the system’s state.

Stay tuned!




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s