Observer pattern is a common pattern in practice. Here I would like to introduce and show how to implement it in Java.
Introduction
Observer pattern is often used when one object needs to be monitored by many other Observer. When the status of an object changes, Observers will receive notifications and then update automatically.
Class Diagram

Advantages

  • Reducing the dependence between Objects which need to be monitored with Observers.
  • Add or remove Observers independently at any time.

Disadvantages

  • Orders of the announcement are independent.
  • In certain cases, sending notifications to all Observers is not necessary.

Implement

Based on Diagram class, we need an interface Observer to create abstraction layers to monitor subjects as follows:

Interface Subject is classes which need to be monitored. There are 3 main methods in Interface Subject are:

  • Attach: add an Observer to the list of objects being tracked.
  • Detach: remove an Observer from the list of objects being tracked.
  • NotifyObserver: notice the changes to the objects in the watchlist
After building the two above interfaces, we will implement their respective subclasses.

We will analyze problems in one soccer game. When there is one goal, it will be informed to other information pages immediately.

Create  class FootbalMatch which has some characteristics namely homeScorehomeTeamName and awayScoreawayTeamName  which is corresponding to goals with the name of the home team and away team respectively.

After completing class FootbalMatch  , class Observer will be implemented as follows

Applied in practice

Observer pattern is often used in the following cases:

Processing with: Java Swing and .NET using  Observer patterns to handle events on the interface.

MVC patterns: In MVC patterns, the corresponding View is Observers, and Model is Subject.

Link reference:

http://www.oodesign.com/observer-pattern.html

Hai Thanh Duong

Translator: Nhu Ngoc

Related posts: