Observer Pattern

Observer Pattern is one of the behavioral design patterns which defines a one-to-many relationship between the objects so that when the state of one object, called as Subject, changes, all its dependents, called as Observers, are notified and updated automatically by calling their methods.

It is also known as a Publish-Subscriber pattern.

Mainly, this pattern is used to implement distributed event handling systems. It is also a key part in the Model-View-Controller (MVC) architectural pattern.

 

Structure

The structure of the Observer pattern is shown below:

observer-pattern-class

Figure: Observer Pattern Structure

Here, Subject has a list of Observer as observers, e.g. ConcreteObserverA and ConcreteObserverB. Whenever there is a change in state of object in Subject, all the objects of a concrete implementation of Observer class get updated via their update function.

 

Example:

Here we've presented you a more practical example that will help you to understand this pattern more.

The class diagram of the system is:

stockmarket-class-diagram

Figure: Observer Pattern Example – Stock Update Notification

Here, StockMarket is the subject and StockBroker is the Observer. StockBroker has two concrete implementations as StockBuyer and StockViewer. So, whenever stockMarket object is changed, these two concrete observers get an update via their function update().

Let's look at the sequence diagram to make understanding more clear.

obeserver-pattern-sequence

Figure: Sequence Diagram for Stock Market add

Whenever a stock value is updated for a symbol, then subscribers, StockBuyer  and StockViewer , of the StockMarket  will get an update information.

Java Implementation

Below is the java implementation of the system described above.

Let us start by creating an interface StockBroker as an interface for an observer.

import java.util.Map;
/**
 * Observer interface
 */
interface StockBroker {
    void update(Map<String, Double> stockList);
}

These are the concrete implementations of the abstract observer.

import java.util.Iterator;
import java.util.Map;

/**
 * Here, StockBuyer and StockViewer are concrete Observers
 */
public class StockBuyer implements StockBroker {

    public void update(Map<String, Double> stocks) {
        System.out.println("StockBuyer: stockList is changed:");
        stocks.forEach((symbol, value) -> System.out.println(symbol + " - $" + value));
    }
}
public class StockViewer implements StockBroker {

    public void update(Map<String, Double> stocks) {
        System.out.println("StockViewer: stockList is changed:");
        stocks.forEach((symbol, value) -> System.out.println(symbol + " - $" + value));
    }
}

Now, we've created a subject class that notifies all the observers upon change on its state.

/**
 * Subject
 */
public abstract class AbstractStockMarket {
    private List<StockBroker> stockBrokers = new ArrayList<StockBroker>();

    public void addStockBroker(StockBroker stockBroker) {
        stockBrokers.add(stockBroker);
    }

    public void notifyStockBroker(Map<String, Double> stockList) {
        for (StockBroker broker : stockBrokers) {
            broker.update(stockList);
        }
    }

    public abstract void addStock(String stockSymbol, Double price);

    public abstract void update(String stockSymbol, Double price);
}

We could have combined the above two subject classes. However, the separation of them provides an extra layer which provides the extensibility on future.

The following code represents the concrete subject.

/**
 * It is concrete Subject
 */
public class StockMarket extends AbstractStockMarket {

    private Map<String, Double> stockList = new HashMap<>();

    public void addStock(String stockSymbol, Double price) {
        stockList.put(stockSymbol, price);
    }

    public void update(String stockSymbol, Double price) {
        stockList.put(stockSymbol, price);
        notifyStockBroker(stockList);
    }
}

So finally, here is application class to implement above classes.

/**
 * Client
 */
public class Application {
    public static void main(String[] args) {
        AbstractStockMarket market = new StockMarket();

        StockBroker buyer = new StockBuyer();
        StockBroker viewer = new StockViewer();

        market.addStockBroker(buyer);
        market.addStockBroker(viewer);

        market.addStock("ORC", 12.23);
        market.addStock("MSC", 45.78);
        System.out.println("===== Updating ORC =====");
        market.update("ORC", 12.34);
        System.out.println("===== Updating MSC =====");
        market.update("MSC", 44.68);
    }
}

The output of the program is:

===== Updating ORC =====
StockBuyer: stockList is changed:
ORC - $12.34
MSC - $45.78
StockViewer: stockList is changed:
ORC - $12.34
MSC - $45.78
===== Updating MSC =====
StockBuyer: stockList is changed:
ORC - $12.34
MSC - $44.68
StockViewer: stockList is changed:
ORC - $12.34
MSC - $44.68

You can see every subscriber gets an update notification when there is a change in the price of the stock.

Point to be noted:

This pattern can cause memory leaks as in basic implementation it requires both explicit attachment and explicit detachment because the subject holds strong references to the observers, keeping them alive. This also referred to as the lapsed listener problem. 

This issue can be eliminated by the subject by holding weak references to the observers. 

Conclusion

This post talked about the summarized form of the Observer Design Pattern, as one of the GOF patterns, with a simple example. I have created a series of design patterns in very simple words. You can take a look at them in my personal blog.

The source code for all example presented above is available on GitHub.

Singleton Pattern
Strategy Pattern