Thursday, May 7, 2015

Observer Pattern example



package designpatterns;

/*
 * Observer Pattern example
 */

class WeatherData {

    float temperature;
    float humidity;
    
    public float getTemperature(){
        return temperature;
    }
    
    public float getHumidity() {
        return humidity;
    }
    
    public void setTemperature(float t) {
        temperature = t;
    }
    
    public void setHumidity(float h) {
        humidity = h;
    }
}

/*
 * The below interface adds functionality to add, remove subscribers/clients 
 *  to the internal list so that they can be notified whenever the state of
 *  the weather changes.
 */
 
interface WeatherNotifier {
    public void notify();
    public void addListener(Object client);
    public void removeListener(Object client);
}

/*
 * WeatherData after implementing the above interface
 */

class WeatherData implements WeatherNotifier {
    private List subscribers;
    {
        subscribers = new ArrayList();
    }
    
    public void notify() {
        // notify/wake up all the subscribers to update their view with latest state information
        Iterator iterator = subscribers.iterator();
        while (iterator.hasNext()) {
            iterator.next().update();
        }
    }

    @Override    
    public void addListener(Object client) {
        subscribers.add(client);
    }
    
    @Override
    public void removeListener(Object client) {
        subscribers.remove(client);
    }

   public void setTemperature(float t) {
        temperature = t;
        dataChanged();
    }
    
    public void setHumidity(float h) {
        humidity = h;
        dataChanged();
    }
    
    private void dataChanged() {
        notify();
    }

    public float getTemperature(){
        return temperature;
    }
    
    public float getHumidity() {
        return humidity;
    }

}

interface WeatherReader {
    public void update();
}

class WeatherClient implements WeatherReader{
    WeatherData source;
    
    public void update() {
        System.out.println("Temperature is " + source.getTemperature());
        System.out.println("Humidity is    " + source.getHumidity());       
    }
}