43

Observer Design Pattern in a Nutshell

 5 years ago
source link: https://www.tuicool.com/articles/hit/z2aaie6
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Observer pattern, also known as the Publish-Subscriber pattern, is one of the behavioral design patterns that defines a one-to-many relationship between objects. For example, when the state of one object, Subject , changes, all its dependents,  Observers , are notified and updated automatically by calling their methods.

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:

ArQVr23.png!web

Figure: Observer Pattern Structure

Here, Subject  has a list of Observers , e.g.  ConcreteObserverA and ConcreteObserverB . Whenever there is a change in state of an object in Subject all of the objects of the concrete implementation of the Observerclass will be updated via their update function.

Example

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

The class diagram of the system is:

2YZB3iz.png!web

Figure: Observer Pattern Example - Stock Update Notification

Here, StockMarket   is the subject   and  StockBroker is the ObserverStockBroker   has two concrete implementations: StockBuyer and StockViewer . So, whenever the  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.

EnAryy2.png!web

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 updated information.

Java Implementation

Below is the Java implementation of the system described above.

Let's start by creating the interface StockBroker as an interface for the 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 the change in 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 two above Subject classes. However, the separation of them provides an extra layer and the extensibility on future classes.

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 the application class used to implement the 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

Conclusion

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

This issue can be eliminated by the Subject holding weak references to the Observers.

The source code for all example presented above is available on GitHub with an additional example of a banking application.

Happy coding!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK