DEV Community

Cover image for Observer Design Pattern Tutorial in java
Ashis Chakraborty
Ashis Chakraborty

Posted on • Edited on

Observer Design Pattern Tutorial in java

When you’re trying to picture the Observer pattern, a Group subscription service with its group being the publisher and users as subscribers is a good way to visualize the pattern.
You follow a group of your interest to get updates of the group. So you are a subscriber/follower of that group. Now if a post is updated, a notification from the group will appear in your timeline. You are the subscriber and the group is the publisher and the group has your profile information so that when a new post is updated, it sends you a notification.

This kind of subscription mechanism is where we need observer design pattern.

For understanding observer, we need to divide this pattern into three parts.
i) Subject/Publisher ii) Observer/Subscriber, and iii) Client.
In observer pattern, we call the publisher the SUBJECT and the subscribers the OBSERVERS. Client-side means just the main function, so no need to worry about that.

Class diagram is given below:

Alt Text

Figure: Class Diagram for Observer Pattern

#Code link

If you are new to design pattern please don’t copy-paste the code, try to write the code yourself, it will do wonders to your understanding about the pattern.

#Main article link

Let's continue:

Subject / Publisher:

Subject in the Observer pattern has three tasks:
i) Provide methods to register and remove observer.
ii) Maintains a list of its observers/subscribers.
iii) And notify them automatically when any state changes. The Subject broadcasts events to all registered Observers.

Let's define an interface as Subject in observer pattern. This is java interface. You can only declare function methods in the interface. Any class implements it must define the functions.

/*
Sample code for observer design pattern
This is the interface which must be implemented by a class
to be called as subject in observer pattern
*/
public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();
}
Enter fullscreen mode Exit fullscreen mode

Group Class is our subject here. It has to implement the subject interface.

/*
Sample code of Observer design pattern
This class implements Subject interface.
Users can register to and deregister from the list to become observer
*/

import java.util.ArrayList;
import java.util.*;

class Group implements Subject{ // this class is called subject in observer design pattern

    private List<Observer> observers = new ArrayList<>();//subscriber/observer list
    private String post; 
    private String name;

    Group(String name){
          this.name = name;
    }

    public void newPost(String post) {
        this.post = post;
        notifyObserver();   //this function notifies new posts to observers
    }

    public void notifyObserver() {
        for (Observer observer : observers) {
            observer.update(this.getPost());    //update posts for observers
        }
    }

    public void registerObserver(Observer o) {
        observers.add(o); //add observer object to list
    }

    public void removeObserver(Observer o) {
        observers.remove(o); //remove observer object from list 
    }

    public String getName() {
        return name;
    }

    public String getPost() {
        return post;
    }
}
Enter fullscreen mode Exit fullscreen mode

Observer / Subscriber:

Observers subscribe and unsubscribe themselves to the Subject. Normally objects which are observers perform two tasks:
i) Uses methods provided by the Subject to subscribe and unsubscribe as an observer.
ii) Implements Observer interface to get update from Subject.

Now we need an interface for observer.

/*
Any class which implements this interface 
will be called observer
in observer design pattern
*/
public interface Observer {
    public void update(String post);
}
Enter fullscreen mode Exit fullscreen mode

User class is our observer, so it must implement the interface to get notification from Group.

/*
User implement observer  interface.
Register as observer in Group
Get update from Group through update()
Deregister from Group
*/

class User implements Observer {

    private String name;
        User(String name){
    this.name = name;
    }

    public void Subscribe(Group grp) {
    grp.registerObserver(this); //register as observer to group
    System.out.print("\n"+this.name+" subscribes "+grp.getName()+"\n");
    }

    public void unSubscribe(Group grp) {
    grp.removeObserver(this);  //unsubscribe from Group class
    System.out.print("\n"+this.name+" unsubscribes "+grp.getName()+"\n");
    }

    public void update(String post) {
        System.out.print("\n"+this.name +" got new post: " + post +"\n");
    }

    public String getName() {
        return name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Client Part:
It's actually the main function. Here in client we create a group and take input for some users and those users subscribe to the group. When a new post is entered in the group, all the subscribed users get notification. The last user unsubscribes the group. So, next time a new post does not reach that user.

/*This can be called client in design pattern
Actually the main function.
Takes input of 4 user name and subscribe to group
Sends a notification to 4 users.
Unsubscribe last person.
Send another notification to 3 users
*/
import java.util.Scanner;

public class ObserverTest {
    private static Scanner scan;

    public static void main( String[] args ) {
        Group grp = new Group("DesignPatternGroup");

        scan = new Scanner(System.in);
        User u = new User("");

        for (int i = 1; i <= 4; i++) { //takes input of four users
            System.out.print("\nEnter a user name: ");
            String name = scan.nextLine();
            u = new User(name);
            u.Subscribe(grp); //all the users subscribe to designpattern group
        }
        System.out.print("\nEnter a new Post: ");
        grp.newPost(scan.nextLine()); //this post will be notified to 4 users

        u.unSubscribe(grp); // the last user unSubscribe group

        System.out.print("\nEnter another Post: ");//take another new post
        grp.newPost(scan.nextLine()); // now 3 subscribed users will get notification
    }
}
Enter fullscreen mode Exit fullscreen mode

Main article is published in medium. Link is below if you need more explanation:
#Main article link

Top comments (0)