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 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 list of Observer as observers, e.g. ConcreteObserverA and ConcreteObserverB. Whenever there is change in state of object in Subject, all the objects of 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:

observer pattern example

Figure: Observer Pattern Example

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 update via their function update().

Lets look at the sequence diagram to make understanding more clear.

obeserver-pattern-sequence

Figure: Sequence Diagram for Stock Market add

 

Java Implementation

Below is the java implementation of the system described above.

Let us start by creating an interface StockBroker as an interface for 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> stocklist) {
        System.out.println("StockBuyer: stockList is changed:");
        Iterator iter = stocklist.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            Double value = (Double) entry.getValue();
            System.out.println(key + " - $" + value);
        }
    }
}
public class StockViewer implements StockBroker {

    public void update(Map<String, Double> stocklist) {
        System.out.println("StockViewer: stockList is changed:");

        Iterator iter = stocklist.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            Double value = (Double) entry.getValue();
            System.out.println("StockViewer " + key + " - $" + value);
        }
    }
}

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

/**
 * Subject
 */
public class Subject {

    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);
        }
    }
}
/**
 * Subject
 */
public abstract class Market extends Subject {
    Map<String,Double> stockList = new HashMap<String,Double>();
    public Map<String, Double> getStockList() {
        return stockList;
    }
}

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

The following code represents the concrete subject.

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

    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) {
        StockMarket 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);
        market.update("ORC", 12.34);
        market.update("MSC", 44.68);
    }
}

The ouput of the program is:

StockBuyer: stockList is changed:
ORC - $12.23
MSC - $ 45.78
StockViewer: stockList is changed:
Stockviewer ORC - $12.23
Stockviewer MSC - $ 45.78

StockBuyer: stockList is changed:
ORC - $12.34
MSC - $ 44.68
StockViewer: stockList is changed:
Stockviewer ORC - $12.34
Stockviewer MSC - $ 44.68

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 refered as the lapsed listener problem. 

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

Singleton Pattern
Strategy Pattern