Observer Pattern Demo

package ObserverPattern; // Observer interface Observer { void update(float temperature); }
package ObserverPattern; class MobileApp implements Observer { public void update(float temperature) { System.out.println("Mobile App: Temperature changed to " + temperature); // Perform specific behavior based on temperature update } }
package ObserverPattern; // Concrete Observers class WeatherDisplay implements Observer { public void update(float temperature) { System.out.println("Weather Display: Temperature changed to " + temperature); // Perform specific behavior based on temperature update } }

Driver:

In the example above, the WeatherStation represents the subject (observable) that maintains a list of observers and provides methods to register, remove, and notify them. The Observer interface defines the update() method, which is implemented by concrete observers like WeatherDisplay and MobileApp. Each observer registers with the subject to receive updates.

When the state of the subject (temperature in this case) changes, the subject notifies all registered observers by calling their update() method. The observers receive the updated temperature and perform specific actions based on the temperature change.

By using the Observer pattern, the subject (WeatherStation) and observers (WeatherDisplay, MobileApp) are decoupled, allowing for flexible and modular designs. The subject doesn't need to know the specific details of its observers, and observers can easily be added or removed without affecting other parts of the system. This pattern is especially useful in scenarios where changes in one object need to be propagated to multiple other objects in a loosely coupled manner.

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark