observer and observable in java example

Emerald 48 Published: 12/09/2024

observer and observable in java example

I'm happy to help!

Observer Design Pattern: A Simple Java Example

The Observer design pattern is a behavioral pattern that allows an object (the subject or observable) to notify other objects (observers) when its state changes.

Here's a simple example in Java:

// The Subject, Observable class

public interface Subject {

void registerObserver(Observer observer);

void removeObserver(Observer observer);

void notifyObservers();

}

// The Observer class

public abstract class Observer {

protected String name;

public Observer(String name) {

this.name = name;

}

// Define an update method which will receive the notification

public abstract void update();

}

// A specific ConcreteObserver for Temperature

public class TemperatureObserver extends Observer {

public TemperatureObserver(String name) {

super(name);

}

@Override

public void update() {

System.out.println("TemperatureObserver: Temperature has changed!");

}

}

// Another specific ConcreteObserver for Humidity

public class HumidityObserver extends Observer {

public HumidityObserver(String name) {

super(name);

}

@Override

public void update() {

System.out.println("HumidityObserver: Humidity has changed!");

}

}

// The WeatherStation, which is the subject observable

public class WeatherStation implements Subject {

private List observers;

private int temperature;

public WeatherStation() {

this.observers = new ArrayList<>();

this.temperature = 0;

}

@Override

public void registerObserver(Observer observer) {

this.observers.add(observer);

}

@Override

public void removeObserver(Observer observer) {

this.observers.remove(observer);

}

@Override

public void notifyObservers() {

for (Observer observer : observers) {

observer.update();

}

}

// The actual weather station logic goes here...

public void setTemperature(int temperature) {

System.out.println("WeatherStation: Temperature has changed to " + temperature);

this.temperature = temperature;

notifyObservers(); // Notify all registered observers

}

}

public class Main {

public static void main(String[] args) {

WeatherStation weatherStation = new WeatherStation();

TemperatureObserver tempObserver = new TemperatureObserver("Temp Observer");

HumidityObserver humidityObserver = new HumidityObserver("Humidity Observer");

weatherStation.registerObserver(tempObserver);

weatherStation.registerObserver(humidityObserver);

// Simulate temperature change

weatherStation.setTemperature(30);

// Simulate another temperature change

weatherStation.setTemperature(20);

// Remove the temperature observer, no notifications should be sent for this change

weatherStation.removeObserver(tempObserver);

// Another temperature change after removing tempObserver

weatherStation.setTemperature(10);

}

}

This example demonstrates how multiple observers (TemperatureObserver and HumidityObserver) can register themselves with a subject (WeatherStation). When the WeatherStation's state changes, it notifies all registered observers by calling their update methods.

The key benefits of this design pattern are:

Decoupling: The observers are decoupled from each other and the weather station. They only depend on the Subject interface. Notification: The subject (WeatherStation) can notify multiple observers about state changes without having a direct reference to them.

In the provided example, when the temperature in WeatherStation changes, it notifies all registered TemperatureObserver and HumidityObserver instances.

observer design pattern in java real time example

The Observer Design Pattern is a behavioral design pattern that allows an object to notify other objects about changes to its state. This pattern is commonly used when multiple objects need to be notified of changes to another object.

In Java, the Observer pattern can be implemented using the following steps:

Define an interface for observers: Create an interface Observer that specifies the update method. This method will be called on each observer whenever the state of the subject changes. Define a subject class: Create a class Subject that implements the Observable interface (in Java, this is typically implemented by extending java.util.Observable). The Subject class maintains a list of observers and provides methods to add, remove, and notify observers when its state changes.

Here's an example of how you could implement the Observer pattern in Java:

// Interface for Observers

interface Observer {

void update(String message);

}

// Class representing the Subject (observable)

class WeatherStation extends java.util.Observable {

private String weather;

public void setWeather(String weather) {

this.weather = weather;

setChanged();

notifyObservers("The current weather is: " + weather);

}

// Method to add observers

public void addObserver(Observer o) {

super.addObserver(o);

}

}

// Concrete Observer class that displays the weather forecast

class WeatherForecastDisplay implements Observer {

@Override

public void update(String message) {

System.out.println(message);

}

}

public class Main {

public static void main(String[] args) {

// Create a WeatherStation (Subject)

WeatherStation weatherStation = new WeatherStation();

// Create and add a WeatherForecastDisplay as an observer

weatherStation.addObserver(new WeatherForecastDisplay());

// Set the initial weather state (initially sunny)

weatherStation.setWeather("Sunny");

// Set the weather to change (now it's cloudy)

weatherStation.setWeather("Cloudy");

// Set the weather again, and observers will be notified

weatherStation.setWeather("Rainy");

}

}

In this example, the WeatherStation class is a subject that can have multiple Observers (like WeatherForecastDisplay) subscribed to it. When the weather state changes (setWeather()), all registered observers are notified through the update() method.

The WeatherForecastDisplay class displays the updated weather forecast to the user. By registering as an observer with the WeatherStation, it can receive updates whenever the weather changes.

This example demonstrates how the Observer pattern allows objects (observers) to be decoupled from each other, making it easier to maintain and extend the system without affecting existing code.

In real-life scenarios, the Observer pattern is used in:

GUI applications to update UI components when the state of an object changes. Web services to notify clients about changes to data. Financial systems to inform traders about market updates. Weather services to alert users about weather changes.

By implementing the Observer pattern, you can create robust and scalable software systems that adapt easily to changing requirements.