Observer design pattern in Java

By | September 9, 2023

The Observer design pattern is a Behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependent objects (observers) are notified and updated automatically. This pattern is also known as the Publish-Subscribe pattern.

Observer design pattern real world example

Let’s understand the observer design pattern with a real-world example. Let’s say we are building a series of Apache Kafka tutorials. Now, if one of the readers reads an article and is waiting for other articles to get published, He or she has to visit our website daily to check whether a new article has been published or not. Instead of this, the readers can subscribe to our mail box, and as soon as any new article gets published, they get notified automatically.

Fig 1- Observer design pattern

In this example, our website became the subject, and the readers became the observers. As soon as the status of the subject changes, all the observers will be notified.

Components of Observer design pattern

  1. Subject: It is an interface whose state changes will be notified to all the observers.
  2. Observer: This is the interface that defines the update or notification method for the observers.
  3. Concrete Subject: This is the implementation class of the subject interface. It maintains the state of the subject and sends an update or notification to observers when the subject’s state changes.
  4. Concrete Observer: It is the implementation of the observer interface that provides the definition for the update or notification method of the observer.

Example

In this example, to understand the observer design pattern, we implement the website and their readers scenario as the publish-subscribe model shown in the above figure-1.

Steps to implement Observer design pattern

Step 1- Create a Subject interface

In this step, we create an interface and name it Subject. It has two methods, subscribe() and notification(), which represent the features of the website.

Java
/**
 * In this example,
 * Subject represents features of our web site
 * 
 * @author paulsofts
 * */
public interface Subject {

	public void subscribe(Observer observer);
	public void notification();

}

Step 2- Create Observer interface

Above, we can see our subscribe() method takes a parameter, Observer. In our example, the observer represents the features of the readers of the website. It has one method, getNotification(), which notifies the readers as soon as any new article is published on the website.

Java
/**
 * In this example,
 * Observer represents features of readers
 * 
 * @author paulsofts
 * */

public interface Observer {
	
	public void getNotification();

}

Step 3- Create concrete implementation of Subject interface

Afterward, we create a concrete class- Website, which implements the Subject-Interface. It will be responsible for sending notification to the observers, as the state of the object (website) changes, which is whenever a new article gets published, it will send notification to all the observers.

Java
import java.util.ArrayList;
import java.util.List;

/**
 * Website class represents our website
 * which implements the Subject to have features of
 * subscribing readers and sending notification 
 * 
 * @author paulsofts
 * */
public class Website implements Subject {

	//readers_list stores the list of all the readers of the website
	private List<Observer> readers_list = new ArrayList<Observer>();

	//this method is used to add all the readers to the readers_list
	@Override
	public void subscribe(Observer observer) {
		this.readers_list.add(observer);
	}

	//this method is used to provide notification to all the readers of
	//readers_list
	@Override
	public void notification() {
		for (Observer observer : readers_list) {
			observer.getNotification();
		}
	}
}

Step 4- Create concrete implementation of Observer interface

Now, we provide the implementation of our Observer interface. For this, we create a new class Reader, which holds the information related to observers and has implementation of getNotification() method. So that all the observers will get the notification.

Java
/**
 * Reader class implements Observer
 * So that, readers get the notification for
 * newly published articles
 * 
 * @author paulsofts
 * */
public class Reader implements Observer {
	
	private String name;
	
	public Reader(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void getNotification() {
		System.out.println("Hi " + this.name + ", " + "Article Published! Check it out.");
	}
}

Step 5- Create Main class

Lastly, we will create our Main Class. It contains the Subject’s object and list of Observers. As the state of the subject changes, all the observers will get notified about the change.

Java
import java.util.ArrayList;
import java.util.List;

/**
 * 1. First, we create our Subject object: Website
 * 2. Create list of Observers: readers_list
 * 3. In loop, each reader are subscribing to Subject
 * 4. Lastly, as Subject's state changes, all the Observers
 *    get notification for that change
 * 
 * @author paulsofts
 * */
public class Main {
	
	public static void main(String[] args) {
		
		Website website = new Website();
		
		//These are the list of readers
		List<Reader> readers_list = new ArrayList<Reader>();
		readers_list.add(new Reader("Aparna"));
		readers_list.add(new Reader("Rahul"));
		readers_list.add(new Reader("Anjali"));
		readers_list.add(new Reader("Shubham"));
		
		//each readers of website are subscribing to the website
		for(Reader reader : readers_list) {
			website.subscribe(reader);
		}
		
		//state of only one object(website) changes, it will give
		//notification to all the observers(subscribed readers) about that change
		website.notification();
		
	}
}

Step 6- Test application

We will run our main class to test the Observer design pattern. As we run our application, we get the following output:

Observer design pattern in Java
Fig 2- Observer design pattern: Output

Leave a Reply

Your email address will not be published. Required fields are marked *