The subject has an interface that defines methods for attaching and detaching observers from the subject's collection of observers. This interface also features a notification method. This method should be called when the state of the subject changes. This notifies the observers that the subject's state has changed. The observers have an interface with a method to update the observer. This update method is called for each observer in the subject's notification method. Since this communication occurs via an interface, any concrete observer implementing the observer interface can be updated by the subject. This results in loose coupling between the subject and the observer classes.
Now we'll look at an example of the observer pattern. We'll start by creating an interface for the subject called WeatherSubject. This will declare three methods: addObserver(), removeObserver(), and doNotify().
WeatherSubject.java
package com.cakes; public interface WeatherSubject { public void addObserver(WeatherObserver weatherObserver); public void removeObserver(WeatherObserver weatherObserver); public void doNotify(); }We'll also create an interface for the observers called WeatherObserver. It features one method, a doUpdate() method.
WeatherObserver.java
package com.cakes; public interface WeatherObserver { public void doUpdate(int temperature); }The WeatherStation class implements WeatherSubject. It is our subject class. It maintains a set of WeatherObservers which are added via addObserver() and removed via removeObserver(). When WeatherSubject's state changes via setTemperature(), the doNotify() method is called, which contacts all the WeatherObservers with the temperature via their doUpdate() methods.
WeatherStation.java
package com.cakes; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class WeatherStation implements WeatherSubject { SetWeatherCustomer1 is an observer that implements WeatherObserver. Its doUpdate() method gets the current temperature from the WeatherStation and displays it.weatherObservers; int temperature; public WeatherStation(int temperature) { weatherObservers = new HashSet (); this.temperature = temperature; } @Override public void addObserver(WeatherObserver weatherObserver) { weatherObservers.add(weatherObserver); } @Override public void removeObserver(WeatherObserver weatherObserver) { weatherObservers.remove(weatherObserver); } @Override public void doNotify() { Iterator it = weatherObservers.iterator(); while (it.hasNext()) { WeatherObserver weatherObserver = it.next(); weatherObserver.doUpdate(temperature); } } public void setTemperature(int newTemperature) { System.out.println("\nWeather station setting temperature to " + newTemperature); temperature = newTemperature; doNotify(); } }
No comments:
Post a Comment