Java — Observer Design Pattern Example using Java

Prabhu Kumar
4 min readNov 30, 2020

--

The Observer Design Pattern maintains one-to-many dependency between Subject (Observable) and its dependents (Observer) in such a way that whenever state of Subject changes, its dependents get notified

Structure Summary

  • Differentiate between the core (or independent) functionality and the optional (or dependent) functionality
  • Model the independent functionality with a “subject” abstraction
  • Model the dependent functionality with an “observer” hierarchy
  • The Subject is coupled only to the Observer base class
  • Observers register themselves with the Subject
  • The Subject broadcasts events to all registered Observers

The participant classes in the observer pattern are

Subject

Interface or abstract class defining the operations for attaching and de-attaching observers

ConcreteSubject

Maintain the state of the object and when a change in the state occurs it notifies the attached Observers

Observer

Interface or abstract class defining the operations to be used to notify this object

ConcreteObservers

Concrete Observer implementations — ConcreteObserver1, ConcreteObserver2

UML Diagram

Implementation steps

Step 1 — Create the subject interface

Step 2 — Create concrete subject class with state

Step 3 — Create the observer interface with update method

Step 4— Create the concrete observers

Step 4 — Create the demo program

Code Example

Here we have taken an example from the e-commerce store, where initially for a particular product stock is not available. Whenever the stock is available for that product, we should notify all the customers that are registered for this product.

Step 1:

public interface Subject {public void addObserver(Observer observer);public void removeObserver(Observer observer);public void notifyObservers();}

Here we have provided the “Subject” interface with the methods to add and remove observers and notify them if there are any changes to the state of the subject.

Step 2:

public class Product implements Subject {private List<Observer> customers;private String productName;private String productType;private String productPrice;private String availability;public Product(String productName, String productType, StringproductPrice, String availability) {customers = new ArrayList<Observer>();this.productName = productName;this.productType = productType;this.productPrice = productPrice;this.availability = availability;}@Overridepublic void registerObserver(Observer observer) {customers.add(observer);}@Overridepublic void removeObserver(Observer observer) {customers.remove(observer);}public void setAvailability(String availability) {this.availability = availability;System.out.println("Availability changed from Not Available to Available");notifyObservers();}@Overridepublic void notifyObservers() {System.out.println("Product Name :" + this.productName + ", Product Type :" + this.productType + ", Product Price :" + this.productPrice + " is available now. So notifying all the users");for(Observer customer : customers) {customer.update(this.availability);}}

Here we have created the concrete subject “Product” which has 4 product attributes and list of customers and implemented the methods for the addition and removal of customers. The “notifyObservers” method simply loops through the list of customers and sends an update to each of the customer.

Step 3:

public interface Observer {public void update(String availability);}

Here we have created “Observer” interface with “update” method. When there is a change in the subject, the observers should update.

Step 4:

public class Customer implements Observer {private String customerName;public Person(String customerName, Subject subject) {this.customerName= customerName;subject.addObserver(this);}@Overridepublic void update(String availabiliy) {System.out.println("Hello " + this.customerName + ", Product is now " + availabiliy + " on flipkart");}}

Here we have provided implementation for the observer which updates the customer that the product is available for purchase now on flipkart.

Step 5:

public class Demo {public static void main(String[] args) {Product samsungLEDTV = new Product("Samsung LED TV", "LED TV","60000Rs", "Not available");Customer david = new Customer("David", samsungLEDTV);Customer john = new Customer("John", samsungLEDTV);samsungLEDTV.setAvailability("Available");}}

Here when the “setAvailability” method is called on subject, it will call “notifyObservers” method which will loop through each observer and call the “update” method on the customer.

Verify the output

Availability changed from Not available to AvailableProduct Name :Samsung LED TV, Product Type : LED TV, product Price : 60000Rs is available now. So notifying all the usersHello David, Product is now Available on flipkartHello John, Product is now Available on flipkart

Summary

The Observer Pattern is a behavioral design pattern

Use the Observer pattern when changes to the state of one object may require changing other objects. Also use the pattern when some objects in your app must observe others.

I hope this explanation and Observer Design Pattern code example have been helpful. If you like this tutorial please give a clap.

--

--

Prabhu Kumar
Prabhu Kumar

No responses yet