Feeding the Observer design pattern into our brain

Feeding the Observer design pattern into our brain

HI Guys , In this article we are feeding the observer design pattern into our brain.

Definition of Observer design pattern

An observer design pattern is a one-to-many relationship between the objects when one object changes the state all other objects are will get notified and updated automatically.

Oho, you might think let's close this article he started with some object orient jargons I don't want to scare you with the definition but better to put to understand it with simplicity in the coming section.

So let's understand the observer design pattern using the newspaper example

There are two actors present in the newspaper publisher take the example of the times of India.

and the second actor is readers like you and me or some organization like a hotel, hospital airline, etc.

Reader subscribes the newspapers afterward gets the newspaper every day in the morning.

If the reader decides he/she wants to unsubscribe they can. After unsubscription, they will not get the newspaper but the other reader will have it right.

While newspaper publishers remains in the business and other readers like hotel, hospital, airlines will still get the news update till they have subscribed to the newspaper

If you understand the Newspaper subscription model. then you pretty much understand the observer design pattern.

only we call publisher as subject and subscriber as Observers

Publisher +Subscriber = Observer pattern

Let's take a closer look.

Suppose some object manages some bit of information lets call int a

and some groups of objects are interested to get notification when int a gets changes and do some kind of processing on that basis.

In that case, the object which holds the bit of information is called the subject and the group of objects is observers.

Observers can decide if they want to get notified by subscribing to the subject-object and at any point in time observer object can unsubscribe to leave the observer group

let's see the below diagram where subject-object managing the int a data and dog, cat , mouse object subscribes to the subject so whenever the state a will changes dog cat and mouse object will get a notification. In other words cats, dog and mouse are observers of subject-object. on the other hand, duck object is not subscribed to the subject object so it will not get any notification

sc1.png

Now you all understand, what exactly the observer pattern is.

You also got glimpses at what situation we can apply this pattern in the real world. Let me reiterate the situation of applicability of pattern. suppose we have a situation where we have some remote object which maintains the state. and some bunch of objects wants to get notification when that state changes. so we can use observer design patterns to solve the problem.

You must be having the question of how can we implement this pattern in a real-world examples. Before that let's go through the class diagram of the observer design pattern

Screenshot 2022-02-09 at 11.58.42 AM.png

In the above class diagram, we have two interface

  • Subject
  • Observer

Subject Interface contains the add, remove and notify functionality which can use to add remove and notify the observers on runtime.

Concrete observers should implement the Observer interface which has method updates. So whenever the subject update its state then the subject will notify the changing state to the observer by calling its update method

Let's implement the observer design pattern by taking the example Let's assume we have to design a system where one component tracks the changes in temperature and some components need the active changes temperature value so they can behave on the basis of temperature value and control the system to work in the proper way at different temperatures.

So in the case, we need one Subject which tract the temperature value and observers who will observe the temperature value from subject and act accordingly

Subject interface


public interface Subject {
    void registerObserver(IObserver iObserver);
    void removeObserver(IObserver iObserver);
    void notifyStateChange();

}

Concrete Temperature Subject implement Subject interface


import java.util.ArrayList;

public class TemperatureSubject implements  Subject
{
    private  final ArrayList<IObserver> observers;
    private final State state ;

    public TemperatureSubject() {
        state =new State();
        observers= new ArrayList<>();
    }

    @Override
    public void registerObserver(IObserver iObserver) {
        observers.add(iObserver);
    }

    @Override
    public void removeObserver(IObserver iObserver) {


        if(observers.indexOf(iObserver)>-1){
            observers.remove(iObserver);
        }
    }

    public  void  setTemprature(int temprature){
        state.setTemperature(temprature);
        notifyStateChange();
    }
    @Override
    public void notifyStateChange() {

        observers.stream().forEach(observer-> observer.update(state));

    }
}

Registration the Subject with Observers and change the temperature

public class Main {

    public static void main(String[] args) {

     //create subject
     TemperatureSubject subject = new TemperatureSubject();

     //create observers and register them with subject
     TemperatureObserver observer1= new TemperatureObserver(subject,"observer-1");
     TemperatureObserver observer2= new TemperatureObserver(subject,"observer-2");

  //change the state of subject and from there subject will notify the observers

     subject.setTemprature(10);
     System.out.println("------------------------------------------");
     subject.setTemprature(30);
     System.out.println("------------------------------------------");

     //observer1 going to unsubscribe for notification
     observer1.unSubscribe();
     //in this  case only subscriber 2 ca receive the notification
     subject.setTemprature(80);

    }
}

Output :

observer-1 :temperature change :10 c
observer-2 :temperature change :10 c
------------------------------------------
observer-1 :temperature change :30 c
observer-2 :temperature change :30 c
------------------------------------------
observer-2 :temperature change :80 c

Once the observer unsubscribe then he will not receive any notification from the subject

but at any time observer decide to register he can do register as he has reference if subject.

that the biggest benefit of the observer design pattern

Observer design pattern creates loosely coupled design. At any time observers can register and unregister without changing a single line of code in subject or observer.

I hope you get the idea of the observer design pattern.

Remember the Design Principle : Strive for the loosely couple design between the objects that interact

Thanks for reading