An Overview to Understand Observer Pattern in Java

You know how newspaper or magazine subscriptions work:

  1. A newspaper publisher  goes into business and begins publishing newspapers.
  2. You subscribe to particular publisher, and every time there’s a new edition it gets delivered to you. As long as you remain a subscriber, you get new newspapers.
  3. You unsubscribe when you don’t want papers anymore, and they stop being delivered.
  4. While the publisher remains in business, people, hotels, airlines, and other businesses constantly subscribe and unsubscribe to the newspaper.

PUBLISHERS + SUBSCRIBERS = OBSERVER PATTERN

You understand newspaper subscriptions, you pretty much understand the observer pattern, only we call the publishers the SUBJECT and the subscribers the OBSERVERS.

The Observer Pattern Defined

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject’s state changes, the observers get notified.

Example implementing Share Market to Understand Observer Pattern in Java

We are going to create an app that uses the StockData object to update stock rates and notifies to observers.

An Overview Class Diagram of Observer Pattern for implementing Share Market app

The Observer Pattern provides an object design where subjects and observers are loosely coupled.

  • The only thing the subject knows about an observer is that it implements a certain interface (the observer interface). It doesn’t need to know the concrete class of the observer, what it does, or anything else about it.
  • We can add new observers at anytime. Because the only thing, the subject depends on is a list of object that implement the Observer interface, we can add new observer whenever we want. Likewise we can remove the observers anytime.
  • We never need to modify the subject to add new types of Observers.
  • We can reuse subjects or observers independently of each other.

Implementing the Share Market App

We are going to implement using the class diagram. So let’s get started with coding.

Subject interface takes an Observer as an argument, that is, the observer to be registered or removed. Also a method to notify all observers when the subject’s state has changed.

public interface Subject {

  public void registerObserver(Observer o);
  public void removeObserver(Observer o);
  public void notifyObservers();
}

The Observer interface is implemented by all the observers, so they all have to implement the update() method.

public interface Observer {

  public void update(float currentPrice, float previousPrice, float change, float changePercentage);

}

The DisplayElement interface just includes one method, display(), that will call when the display element needs to be displayed.

public interface DisplayElement {

  public void display();

}

Let’s implement the Subject interface in StockData class,

public class StockData implements Subject {
  private ArrayList<Observer> observers;
  private float currentPrice;
  private float previousPrice;
  private float change;
  private float changePercentage;
  
  public StockData() {
    observers = new ArrayList<Observer>();
  }

  @Override
  public void registerObserver(Observer o) {
    observers.add(o);
  }

  @Override
  public void removeObserver(Observer o) {
    int i = observers.indexOf(o);
    if(i >= 0) {
      observers.remove(i);
    }
  }

  @Override
  public void notifyObservers() {
    for(Observer observer : observers) {
      observer.update(currentPrice, previousPrice, change, changePercentage);
    }
  }
  
  public void stockRatesChanged() {
    notifyObservers();
  }
  
  public void setStockRates(float currentPrice, float previousPrice, float change, float changePercentage) {
    this.currentPrice = currentPrice;
    this.previousPrice = previousPrice;
    this.change = change;
    this.changePercentage =changePercentage;
    stockRatesChanged();
  }
}

Now, let’s build those display elements.

  • The constructor is passed the stockData object(the subject) and we use it to register the display as an observer.
  • The display element class implements the Observer so it can get changes from the StockData object.
public class CurrentStockRateDisplay implements Observer, DisplayElement {

  private float currentPrice;
  private float previousPrice;
  private float change;
  private float changePercentage;
  private Subject stockData;

  public CurrentStockRateDisplay(Subject stockData) {
    this.stockData = stockData;
    stockData.registerObserver(this);
  }
  
  @Override
  public void display() {
    this.currentPrice = currentPrice;
    this.previousPrice = previousPrice;
    this.change = change;
    this.changePercentage =changePercentage;
    display();
  }

  @Override
  public void update(float currentPrice, float previousPrice, float change, float changePercentage) {
    System.out.println("Company current price : "+currentPrice+" | previous price : "+previousPrice+" | change : "+change+" | change percentage : "+changePercentage);	
  }

}

Power  up the Share Market App

public class ShareMarket {

  public static void main(String[] args) {
    StockData stockData = new StockData();		
    CurrentStockRateDisplay cd = new CurrentStockRateDisplay(stockData);
    
    stockData.setStockRates(40, 20, 10, 100);
    stockData.setStockRates(20, 10, 10, 100);
    stockData.setStockRates(15, 10, 5, 50);

  }

}

Output

Company current price : 40.0 | previous price : 20.0 | change : 10.0 | change percentage : 100.0
Company current price : 20.0 | previous price : 10.0 | change : 10.0 | change percentage : 100.0
Company current price : 15.0 | previous price : 10.0 | change : 5.0 | change percentage : 50.0

Hope Observer pattern is understood.

Observer Pattern in Java – Extension

So far we’ve rolled our own code for the Observer pattern, but Java has built-in support in several of its APIs. Let’s see about built-in APIs in my next article of Observer Pattern Part II.

Please follow and like us:
error