Design Patterns - 2

NeelNeel
3 min read

Observer Pattern keeps the objects in the know when something about they care happens.

Publishers + Subscribers = Observer Pattern

Only in case of Observer pattern :

Publisher -> Subject / Observable

Subscriber -> Observer

This pattern defines one-to-many relationship between Subject and Observer/s. When the state that Subject is holding, changes, all the subscribers are notified of this change.

Observer Pattern Design:

Subject : An interface having following methods:

public interface Subject {

    public void registerObserver(Observer ob);
    public void removeObserver(Observer ob);
    public void notifyObserver();
}

Observer : An interface having one method:

public interface Observer {

    public void update();
}

Lets build a Weather Monitiring Station.

WeatherData pulls weather information like tempearute, humidity etc to sends it to display device

Subject Class

public intrface Subject {

    public void registerObserver(Observer ob);
    public void removeObserver(Observer ob);
    public void notifyObserver();
}

Observer class

public interface Observer {

    public void update(float temp,float humidity,float pressure);
}

Display Device

public interface DisplayDevice {

    public void display();
}

Implementing Subject Interface - WeatherData

public class WeatherData implements Subject{

    // ArrayList to store observers
    private List<Observer> observers;

    // state that observers are interested in
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData(){
        observers = new ArrayList<Observer>();
    }



    @Override
    public void registerObserver(Observer ob) {
        observers.add(ob);
    }

    @Override
    public void removeObserver(Observer ob) {
            observers.remove(ob);
    }

    @Override
    public void notifyObservers() {
        for(Observer o : observers){
            o.update(temperature,humidity,pressure);
        }
    }

    public void measurementsChanged(){
        notifyObservers();
    }

    public void setMeasurements(float temperature,float pressure,float humidity){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;

        // notify observers
        measurementsChanged();
    }
}

Now lets build the displays . We have two different kinds (these will act as Observers):

Current Conditions Display

Statistics Display (display last three days avg temp)

public class CurrentConditionsDisplay implements Observer,DisplayDevice{

    private float temperature;
    private float humidity;

    // provide a ref to Subject
    private final WeatherData weatherData;

    public CurrentConditionsDisplay(WeatherData weatherData){
        this.weatherData = weatherData;

        // register the observer
        weatherData.removeObserver(this);
    }
    @Override
    public void display() {
        System.out.println("Current condition: " + temperature +" degree F and humidity "+ humidity);
    }


    @Override
    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        System.out.println("hello");
        display();
    }
}

StatisticsDisplay

    private float maxTemp = 0.0f;
    private float minTemp = 200;
    private float tempSum= 0.0f;
    private int numReadings;
    private WeatherData weatherData;

    public StatisticsDisplay(WeatherData weatherData) {
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    public void update(float temp, float humidity, float pressure) {
        tempSum += temp;
        numReadings++;

        if (temp > maxTemp) {
            maxTemp = temp;
        }

        if (temp < minTemp) {
            minTemp = temp;
        }

        display();
    }

    public void display() {
        System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
                + "/" + maxTemp + "/" + minTemp);
    }
0
Subscribe to my newsletter

Read articles from Neel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Neel
Neel