JAVA Developer Guide to start with Observer Design Pattern

Ritvik Singh Chauhan
Javarevisited
Published in
4 min readMay 9, 2022
Photo by Marten Newhall on Unsplash

If you have used KAFKA or JMS, you are likely aware of the publish-subscribe interaction model. In messaging applications, subscriber objects that subscribe to the subject or topic receive a notification when a publisher object generates content on the subject. Subscribers can theoretically be subscribed to more than one publisher. The observer design pattern helps in solving the pub/sub model which allows a number of observer objects to see a subject event.

What is the Observer Pattern?

The observer pattern is one of the behavioral design patterns from the book “Design Patterns: Elements of Reusable Object-Oriented Software”. An observer pattern is used when there is a one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified and updated automatically. In this pattern, the object that watches the state of another object is called the Observer, and the object that is being watched is called the Subject.

All the Social media sites such as Twitter and Facebook are great examples of this pattern. You follow a user and when that user adds content, you along with all other followers of that user receive the notification. Other example includes RSS feeds and email subscription in which you have the option to follow or subscribe, and you receive the latest notification for the new feed.

Observer Pattern JAVA Example

Suppose we are building a cryptocurrency buy/sell application, which allows users to trigger the buy or sell process based on the notification received for price change events. For this example, I will have a few observers which will subscribe to a cryptocurrency. When the cryptocurrency price will be going down, the buyer observer will purchase some stocks. Similarly, in case of cryptocurrency prices rise, seller observers will sell the stocks.

Photo by Jeremy Bezanger on Unsplash

Subject Definition

In the Subject interface, there are three methods declared. addObserver method is for adding subscribers, the removeObserver method is for deleting the existing subscriber and the notifyObservers method is for sending notifications to all subscribers.

Subject Interface

Concrete Subject

For concrete Subject, I have created a CryptoCurrency class with all the implemented methods from the Subject interface along with new fields for the name and price of the cryptocurrency.

Concrete Subject

Observer Definition

In the Observer interface, there is only a single method declared notification, which will be invoked by the concrete subject.

Observer Interface

Concrete Observers

For concrete observers, I have created 3 classes. PriceWatcher class is created to tell the current and previous price of updating CryptoCurrency concrete subject. CryptoCurrencyBuyer class is created for calling external API to buy cryptocurrency if the currency is reaching below a certain amount. Similarly, CryptoCurrencySeller class is created for calling an external API to sell cryptocurrency if the currency is reaching above a certain amount.

First Concrete Observer
Second Concrete Observer
Third Concrete Observer

Observer Pattern in Action

In the demo code below, created a Bitcoin and five observers. All the subscribers are notified when the bitcoin price is updated.

Main Method with Output

Source Code Available at: https://github.com/s3c-d43m0n/Desing-Patterns-in-JAVA/tree/main/Behavioral/Observer

Key Points in the Implementation

  • Here Subject and Observer are interface. But It can be an abstract class as well, not bound to use interface only.
  • Concrete Subject needs to maintain all the Observers in a collection as per the requirement. Here I have used CopyOnWriteArrayList (Fail-Safe) collection to store all observers as I am having some of the Observers which are going to remove themself while being iterated in the notifyObservers method.
  • Need to call notifyObservers method whenever there is a change in the state of Concrete Subject.
  • Each Concrete Observer needs to implement notification method for the action to take based on its requirement to consume the changes in Subject.
  • For each Concrete Observer, need to attach with Subject using addObserver method and detach using removeObserver method.

What’s your favorite design pattern or if you’d like to understand better any other pattern or topic, feel free to reach out to me on LinkedIn or Google Form and I’ll try to cover it next time!

Please share this with all your Medium friends and hit that👏 button below to spread it around even more. Please follow me for future updates. Thanks for reading.

--

--

Ritvik Singh Chauhan
Javarevisited

Tech Enthusiast Software Developer focused on Backend Engineering. Get notified when I publish: https://medium.com/subscribe/@ritvik.singh.chauhan