Design Pattern: Observer Pattern in Java

We use simple examples and diagrams to describe the concept of observer pattern. We also give a simple implementation of the observer pattern in Java. 

What is Observer Pattern

The observer pattern defines a one-to-many relationship between two kinds of objects. The one side is called Subject, which maintains a list of Objects (called observers), and automatically notify each of the observers if something interesting happens. 

The definition of the Observer pattern provided in the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, is:

“One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject’s state, they can simply detach themselves.”

Steps to use Observer Pattern

  1. We create two kinds of Objects: Subject and Observers. 
  2. When we create an observer, we register it to the subject. 
  3. When something interesting happens to the subject, the subject will notify all the observers that have been registered. 
  4. When a particular observer is no longer needed to be notified, the subject can remove it from the list of the observers. 
  5. See the following diagram to understand how server Pattern works.

See the following diagram to understand how Observer Pattern works.

observer pattern

Implement Observer Pattern In Java

Step 1

We create a Subject class, in which there is a container to hold all the Observers that will be registered to this subject. If something interesting happens, the state of the subject will change, and the registered Observers will be notified by calling the observer’s perform() method. 

Step 2

We create two kinds of Observers: ObserverA and ObserverB. Both extend the super class Observer, which has an abstract method perform(). The subClass will override this method to perform something specifically based on the subject’s updated state. 

Step 3

In the driver class, we create a subject, and register two observers to it.  Then we change the subject’s state twice, you can see the observer’s perform() methods are called after the state change. 

Here is the output after executing the program: