Observer Design Pattern in Java

This article explains Observer design pattern in java with UML class diagram. It then takes an example scenario in java and explains it with class diagram and code.

Introduction: Observer Design Pattern is a behavioral design pattern among the Gang Of Four(GOF) Design PatternsArticle on GOF Patterns & their types. Being a behavioral design pattern, the Observer pattern deals with how objects of the designed system interact with each other.

What is Observer Design Pattern
Observer Design Pattern is used when there are multiple subscribers observing updates from a publisher. The publisher, known as Subject, publishes its change of state to its subscribers. Subscribers, known as Observers, receive these changes and update themselves accordingly.

Scenarios in which Observer Design Pattern can be used

  1. Change of an object requires changes to multiple others: When there is an observed object(a.k.a the Subject), then there should be a mechanism to notify its changes to multiple of its observer components which have evinced interest in listening to these changes without the exact quantity of observers being known at design time.
  2. Notification capability needed without tight rules regarding how this notification is used: When the different Observers of notifications from a Subject have there own presentation and\or business logic implementation, but still need to have the capability of getting the latest updates from Subject. I.e. Observers are loosely coupled with the Subject

Class Diagram for Observer Design Pattern

Observer Design Pattern Class Diagram

Explanation of Observer Design Pattern’s Class Diagram

  • Subject is the one being observed. It has attach() & detach() methods to add or remove observers respectively. It uses notify() method to publish its changes to observers\subscribers.
  • Observer objects register\attach themselves to the Subject they want to listen to for updates.
  • ConcreteObserver instances are actual Observer objects which treat the notifications they receive from the Subject in their own individual ways.
  • ConcreteSubject is the actual Subject object whose state change is notified to multiple observers.

Inbuilt Observer Pattern in Java
Java has an inbuilt Observer pattern implementation using the class java.util.Observable (represents Subject) and the interface java.util.Observer(represents an Observer). Concrete Observers in Java need to implement the Observer interface, whereas concrete Subject needs to extend Observable to provide its own notification logic.

The following class diagram shows the relationship between Observer and Observable as defined in the Java SDK follows –

Observer and Observable in JDK Class Diagram

Lets now look at an example implementation of observer design pattern in Java using Observer and Observable.

Observer Design Pattern Example Implementation in Java-Class Diagram

Observer Design Pattern in Java Class Diagram

Code for the classes shown in Java Example’s Class Diagram

Java code for implementing the example shown in class diagram above
//Publisher.java
import java.util.Observable;
public class Publisher extends Observable{
 public void changeStateTo(String newStateName){
  this.setChanged();
  this.notifyObservers(newStateName);
 }
}
//Subscriber1.java
package com.javabrahman.java8.designpatterns.observer;
import java.util.Observable;
import java.util.Observer;
public class Subscriber1 implements Observer{
 String currentPublisherState;
 @Override
 public void update(Observable o, Object arg) {
  System.out.println("New state received by Subscriber 1:"+arg.toString());
  this.currentPublisherState=(String)arg;
 }
}
//Subscriber2.java
import java.util.Observable;
import java.util.Observer;
public class Subscriber2 implements Observer{
 String currentPublisherState;
 @Override
 public void update(Observable o, Object arg) {
  System.out.println("New state received by Subscriber 2:"+arg.toString());
  this.currentPublisherState=(String)arg;
 }
}
//Client.java
public class Client {
 public static void main(String args[]){
  Publisher publisher=new Publisher();
  publisher.addObserver(new Subscriber1());
  publisher.addObserver(new Subscriber2());
  publisher.changeStateTo("assigned");
 }
}
 OUTPUT on running Client.java
New state received by Subscriber 1: assigned
New state received by Subscriber 2: assigned
Explanation of Java Example’s Class Diagram & Code
The Java class diagram above depicts Observer Design pattern implemented for a simple Publish-Subscribe implementation. Let us now go through whats there in Java’s example’s class diagram & corresponding code –

  • Publisher is the Subject. It extends java.util.Observable.
  • Subscriber1 & Subscriber2 are the Observers. They implement java.util.Observer.
  • Client first initiates Publisher. It then adds one instance each of Subscriber1 & Subscriber2 to Publisher’s list of Observers.
  • Client then invokes method changeStateTo() with new state value as “assigned”. Internally Publisher then initiates notifyObservers() with this new state value. Before notifying Publisher calls setStateChanged() which is a requirement of the java’s observer pattern implementation.
  • update() methods of Subscriber1 and Subscriber 2 are called internally by the notifyObservers() method and the new state value received by both in the parameter arg is printed.

Summary
In the above tutorial we understood what is Observer design pattern and the main scenarios in which this pattern is applicable. We then looked at the UML class diagram for Observer Design Pattern & its explanation, a Java Use Case implementing Observer pattern with its class diagram and code for the classes shown in the class diagram, followed by explanation of both the class diagram & code. This concludes the tutorial on Observer design pattern.

 

Digiprove sealCopyright © 2014-2017 JavaBrahman.com, all rights reserved.