[GitHub Repository for Code Samples]
Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
Observer Pattern [Sample Code]
Observer Pattern, as the name suggests, is used in scenarios when updates need to be done at multiple points (Observers) depending on changes in state at another place (Subject). Each of the Observers has to register themselves with the Subject, individually. The Subject should also provide method which allows the Observers to remove themselves. Registered Observers are informed of changes in state through a notify method, usually.
Fig. 1 : Observer (Behavioral) Design Pattern - Class and Sequence Diagram
[Source : Wikipedia]
The provided example is that of a StockBroker application, which involves maintenance of various types of financial information. Subject is the interface in the application which provides a template for the Observed class. StockData is the concrete implementation of Subject and provided implementation of addObserver(), removeObserver() and notifyObservers(). Additionally, it maintains a list of registered observers. IncomeHandler, InvestmentHandler and PortfolioHandler are the various observers used to maintain income, investment and portfolio of a specific StockBroker. All these depend on the constantly fluctuating values of stocks. They are specifically interested in the stockSymbol, stockValue and stockUnits of each individual stock. Each of the observers implements the interface Observer. The Observer interface provide the update() method, which is implemented by each of these concrete classes.
Use StockBroker.java to run the application, Try adding your own observer to this application. Also, you can try picking up these values from a live web service and then writing a custom observer which depends on this.