DEV Community

NOOB
NOOB

Posted on

LLD-4:Weather Monitoring System

Weather Monitoring System - Observer Pattern Implementation

This is an implementation of the Observer design pattern for a weather monitoring application where multiple displays automatically update when the weather station detects temperature changes.

Problem Statement

Building a weather application where a central WeatherStation tracks temperature and multiple display devices (Phone, TV, Smartwatch, etc.) need to show the current temperature. When the temperature updates, all connected displays must update automatically without the WeatherStation knowing the specific details of each display.

Key Challenge: The system must be extensible - adding new display types shouldn't require modifying the WeatherStation code.

Class Diagram

        +------------------+             +-----------------------+
        |     Subject      |             |       Observer        |
        |   (Interface)    |             |      (Interface)      |
        +------------------+             +-----------------------+
        | + add(obs)       |             | + update(temp)        |
        | + remove(obs)    |             +-----------+-----------+
        | + notify()       |                         ^
        +--------+---------+                         |
                 ^                                   | (Implements)
                 | (Implements)                      |
                 |                                   |
        +--------+---------+             +-----------+-----------+----------------+
        |  WeatherStation  |<>---------->|                       |                |
        +------------------+   (List)    |  +----------------+   |  +----------+  |
        | - observers List |             |  |  PhoneDisplay  |   |  | TVDisplay|  |
        | - temperature    |             |  +----------------+   |  +----------+  |
        | + setTemp(t)     |             |  | - userName     |   |  |          |  |
        +------------------+             |  | + update(t)    |   |  | +update()|  |
                                         |  +----------------+   |  +----------+  |
                                         +-----------------------+----------------+
Enter fullscreen mode Exit fullscreen mode

Implementation

package observer.weathermonitoringsystem;

import java.util.ArrayList;
import java.util.List;

/**
 * Main class for the Weather Monitoring System.
 * Implements the Observer Pattern to decouple the Weather Station from the Displays.
 */
public class WeatherMonitoringSystem {

    /**
     * Observer Interface.
     * Defines the contract that all display devices must follow to receive updates.
     */
    interface Observer {
        void update(String temperature);
    }

    /**
     * Subject Interface.
     * Defines the methods to manage subscribers (observers) and notify them.
     */
    interface Subject {
        void addObserver(Observer observer);
        void removeObserver(Observer observer);
        void notifyObserver();
    }

    /**
     * Concrete Subject (Weather Station).
     * Maintains the state (temperature) and the list of subscribers.
     */
    static class WeatherStation implements Subject {
        private final List<Observer> observers = new ArrayList<>();
        private String temperature;

        @Override
        public void addObserver(Observer observer) {
            observers.add(observer);
        }

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

        @Override
        public void notifyObserver() {
            for (Observer observer: observers) {
                observer.update(this.temperature);
            }
        }

        public void setTemperature(String newTemperature) {
            System.out.println("\n[Station] New Temperature measured: " + 
                             newTemperature);
            this.temperature = newTemperature;
            notifyObserver();
        }
    }

    /**
     * Concrete Observer (Phone Display).
     * Displays the temperature on a user's mobile device.
     */
    static class PhoneDisplay implements Observer {
        private final String userName;

        public PhoneDisplay(String userName) {
            this.userName = userName;
        }

        @Override
        public void update(String temperature) {
            System.out.println(" => Phone Display (" + userName + 
                             ") Temperature is now " + temperature);
        }
    }

    /**
     * Concrete Observer (TV Display).
     * Displays the temperature on a large screen.
     */
    static class TVDisplay implements Observer {
        @Override
        public void update(String temperature) {
            System.out.println(" => Tv Display (Living Room): Breaking News! " +
                             "Temperature is " + temperature);
        }
    }

    /**
     * Main driver method to simulate the application flow.
     */
    public static void main(String[] args) {
        WeatherStation station = new WeatherStation();

        Observer shivPhone = new PhoneDisplay("Shiv");
        Observer livingRoomTV = new TVDisplay();

        System.out.println("----Registering Observer----");
        station.addObserver(shivPhone);
        station.addObserver(livingRoomTV);

        // First update: Both displays should receive it
        station.setTemperature("30C");

        System.out.println("\n----Shiv Unsubscribes----");
        station.removeObserver(shivPhone);

        // Second update: Only TV should receive it
        station.setTemperature("28C");
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Features

  • Observer Pattern: Implements one-to-many dependency between objects
  • Loose Coupling: WeatherStation doesn't need to know about specific display implementations
  • Dynamic Subscription: Observers can subscribe and unsubscribe at runtime
  • Automatic Updates: All registered observers are notified automatically when state changes
  • Extensible: New display types can be added without modifying existing code

How It Works

  1. Subject (WeatherStation): Maintains a list of observers and notifies them when temperature changes
  2. Observers (Displays): Implement the Observer interface and receive updates via the update() method
  3. Registration: Displays register with the weather station using addObserver()
  4. Notification: When temperature changes, the station calls notifyObserver() which updates all registered displays
  5. Unsubscription: Displays can unsubscribe using removeObserver()

Sample Output

----Registering Observer----

[Station] New Temperature measured: 30C
 => Phone Display (Shiv) Temperature is now 30C
 => Tv Display (Living Room): Breaking News! Temperature is 30C

----Shiv Unsubscribes----

[Station] New Temperature measured: 28C
 => Tv Display (Living Room): Breaking News! Temperature is 28C
Enter fullscreen mode Exit fullscreen mode

Top comments (0)