Observer Design pattern for Notification System

Observer Design pattern for Notification System

UseCase:

Observer design pattern is used to notify users when the state changes. It is behavioural design pattern.It allows multiple observers (dependent objects) to be notified automatically whenever a subject (observable object) undergoes changes in its state. By employing this pattern, we can build systems that dynamically maintain relationships between objects and enable efficient event handling.

Code :

public interface Observer
	public void update(float temp);
}


public interface Subject{
	void addObserver(Observer obj);
	void removeObserver(Observer obj);
	void notifyObservers();
}


public class WeatherData implements Subject{
	private List<Observer> observers;
	private float temp;


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


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


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


    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temp);
        }
    }


    public void setMeasurements(float temperature) {
	    this.temp = temperature;
	    notifyObservers();
    }
}


public class Display implements Observer {
    private float temperature;


    @Override
    public void update(float temperature) {
        this.temperature = temperature;
        display();
    }


    private void display() {
        System.out.println("Current conditions: " + temperature);
    }
}


public class Main{
	public static void main(String[] args)
	{
		Display display1 = new Display();
        Display display2 = new Display();


        weatherData.addObserver(display1);
        weatherData.addObserver(display2);


        weatherData.setMeasurements(65);
        weatherData.setMeasurements(56);


        weatherData.removeObserver(display2);


        weatherData.setMeasurements(36);
	}
}        

Conclusion:

The Observer design pattern provides an elegant solution for creating maintainable and flexible systems by establishing dependencies between objects. In our weather monitoring example, we demonstrated how the Observer pattern allowed us to easily add new displays without modifying existing code. By employing this pattern, we can enhance the scalability and maintainability of our applications.

Next time you plan to build an application that requires event handling or notifications, consider incorporating the Observer design pattern. Its simplicity and versatility can greatly benefit your project, making it easier to manage and extend in the future. Happy coding!

To view or add a comment, sign in

More articles by Pradeep Singh Rasaputra

Explore content categories