Observer Design Pattern


Observer Design is one of the most important Design Pattern. It has many practical usage like notification services.

  • The main two entities are Publisher(class) and Observer (interface) . Publisher is a class with functions like addObserver and notifyyObservers.
  • Here class WeatherStation is extending Publisher class so that all the functions of Publisher can come to it.
  • Here two Observers Mobile and Monitor is implementing interface Observer. Inside Mobile and Monitor class, they are subscribing to WeatherData inside the constructors.


import java.util.*;

interface Observer {

 void notifyy();

}

class Mobile implements Observer{

    WeatherStation ws;

    public Mobile(WeatherStation ws) {

        this.ws = ws;

        ws.addObserver(this);

    }

    

    @Override

    public void notifyy() {

        System.out.println("Mobile is notified " + ws.getTemperature());

    }

}


class Monitor implements Observer{

    WeatherStation ws;

    public Monitor(WeatherStation ws) {

        this.ws = ws;

        ws.addObserver(this);

    }

    

    @Override

    public void notifyy() {

        System.out.println("Monitor is notified " + ws.getTemperature());

    }

}


class Publisher {

    List<Observer> obs = new ArrayList<>();

    public void addObserver(Observer ob) {

        obs.add(ob);

    }

    

    public void notifyObservers() {

        for(Observer ob : obs) {

            ob.notifyy();

        }

    }

}


class WeatherStation extends Publisher{

    int temperature;

    public  void setTemperature(int temp) {

        this.temperature = temp;

        notifyObservers();

    }

    public int getTemperature() {

        return temperature;

    }

}


public class Main{

    public static void main(String[] args) {

        WeatherStation ws = new WeatherStation();

        Mobile mob = new Mobile(ws);

        Monitor mon = new Monitor(ws);

        ws.setTemperature(10);

        

    }

}



Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.