Subjects
maintain representations of things
they model.
Observers
know how to graphically display
things that subjects model.
float
.
This kind of design requires three kinds of interfaces
,
one for Subjects, one for Observers, and one for the kinds of lists
that each subject will need to record its observers. Here are the
suggested declarations:
public interface Subject { /** Add x to the list of observers **/ public void attach(Observer x); /** Remove x from the list of observers **/ public void detach(Observer x); /** Report the current represented value **/ public float currentValue(); } public interface Observer { /** Deal with the fact that Subject s has changed state **/ public void changeNotification(Subject s); } public interface ObserverList { /** Standard list insert **/ public void add(Observer x); /** Standard list remove **/ public void remove(Observer x); /** For each element e, of the list, send e.changeNotification(s) **/ public void reportChange(Subject s); }The assignment is to:
Temperature
class
that implements Subject
, using the float to represent
the current temperature, an instance of your ObserverList
implementation to maintain the list, and warmBy
and/or similar methods that use the list to do change notifications
upon each update.
WeatherSimulator
class based on threads,
as discussed in class. Depending on the exact details of your
Temperature
class, the WeatherSimulator
will look something like:
public class WeatherSimulator implements Runnable { static final long period = 500; // update period in millisecs static final float offset = 0.5f; // bias for random numbers static final float scale = 1.0f; // scale factor for random numbers protected Temperature temp_; // the temperature object to change public void run() { for (;;) { float delta = (float)((Math.random() - offset) * scale); temp_.warmBy(delta); try { Thread.sleep(period); } catch (InterruptedException ex) {} } } public WeatherSimulator(Temperature t) { temp_ = t; new Thread(this).start(); } }
Observer
. Here are the suggested classes, but
you can substitute others:
start
method that creates a
WeatherSimulator
.