/* * TemperatureModel.java */ import java.util.Observable; /** * In Java, MVC Models can be easily implemented by extending the * java.util.Observable class. The Java Observer/Observable classes provide much * of needed infrastructure for passing registration/notification events back * and forth between Model, View and Controller objects. Here the Observable * superclass contains the methods needed to register observers and notify them * of state changes to the Model. * * This particular class models temperature. It allows allows clients (e.g., * views and controllers) to query and update the data model both in terms of * Fahrenheit and Celsius temperature scales. Upon construction, the model is * initialized to a temperature of 32F (freezing point of water). */ public class TemperatureModel extends Observable { public static final int MAX_TEMP_F = 300; // max allowable temp in the model public static final int MIN_TEMP_F = -200; // min allowable temp in the model private double tempF = 32.0; /** * Return the current temp, expressed in Fahrenheit. Method may be invoked * by View objects. * * @return double temp in F */ public double getF() { return tempF; } /** * Return the current temp, expressed in Celsius. Method may be invoked * by View objects * * @return double temp in C */ public double getC() { return (tempF-32.0)*5.0/9.0; } /** * Modify the current temp, argument expressed in Fahrenheit. Method may * be invoked by Controller objects. Method implements some simple bounds * checking to make sure the new temp falls in the allowed range (between * MAX and MIN allowable temps). */ public void setF(double tempF) { // simple bounds checking - thermometer goes up to 300F and down to -200F if ( tempF > MAX_TEMP_F ) tempF = MAX_TEMP_F; if ( tempF < MIN_TEMP_F ) tempF = MIN_TEMP_F; this.tempF = tempF; setChanged(); // <-- MVC method that signals state change in the Observable object notifyObservers(); // <-- MVC method that notifies all interested observers of the state change } /** * Modify the current temp, argument expressed in Celsius. Method may * be invoked by Controller objects. Method implements some simple bounds * checking to make sure the new temp falls in the allowable range (between * MAX and MIN allowable temps). */ public void setC(double tempC) { // simple bounds checking - thermometer goes up to 300F and down to -200F double val = tempC * 9.0 / 5.0 + 32.0; if ( val > MAX_TEMP_F ) val = MAX_TEMP_F; if ( val < MIN_TEMP_F ) val = MIN_TEMP_F; this.tempF = val; setChanged(); // <-- MVC method that signals state change in the Observable object notifyObservers(); // <-- MVC method that notifies all interested observers of the state change } }