Difference between revisions of "Observer (padrão de desenho)"

From Wiki**3

(Representação de dados)
Line 96: Line 96:
 
Os dados de meteorologia correspondem ao objecto observado.
 
Os dados de meteorologia correspondem ao objecto observado.
  
  <B>public</B> <B>class</B> WeatherData <B>implements</B> Subject {
+
<java5>
     <B>private</B> <B><FONT COLOR="#0095ff">ArrayList</FONT></B> observers;
+
  public class WeatherData implements Subject {
     <B>private</B> <FONT COLOR="#800000">float</FONT> temperature;
+
     private ArrayList<Observer> _observers = new ArrayList<Observer>();
     <B>private</B> <FONT COLOR="#800000">float</FONT> humidity;
+
     private float _temperature;
     <B>private</B> <FONT COLOR="#800000">float</FONT> pressure;
+
     private float _humidity;
 +
     private float _pressure;
 
          
 
          
     <B>public</B> <FONT COLOR="#000080">WeatherData</FONT>() { observers = <B>new</B> <B><FONT COLOR="#0095ff">ArrayList</FONT></B>(); }
+
     public WeatherData() { }
 
          
 
          
     <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">registerObserver</FONT>(Observer o) { observers.<FONT COLOR="#000080">add</FONT>(o); }
+
     public void registerObserver(Observer o) { _observers.add(o); }
 
          
 
          
     <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">removeObserver</FONT>(Observer o) {
+
     public void removeObserver(Observer o) {
       <FONT COLOR="#800000">int</FONT> i = observers.<FONT COLOR="#000080">indexOf</FONT>(o);
+
       int i = _observers.indexOf(o);
       <B>if</B> (i &gt;= <FONT COLOR="#0000ff">0</FONT>) { observers.<FONT COLOR="#000080">remove</FONT>(i); }
+
       if (i >= 0) { _observers.remove(i); }
 
     }
 
     }
 
            
 
            
     <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">notifyObservers</FONT>() {
+
     public void notifyObservers() {
       <B>for</B> (<FONT COLOR="#800000">int</FONT> i = <FONT COLOR="#0000ff">0</FONT>; i &lt; observers.<FONT COLOR="#000080">size</FONT>(); i++) {
+
       for (int i = 0; i < _observers.size(); i++) {
         Observer observer = (Observer)observers.<FONT COLOR="#000080">get</FONT>(i);
+
         Observer observer = _observers.get(i);
         observer.<FONT COLOR="#000080">update</FONT>(temperature, humidity, pressure);
+
         observer.update(temperature, humidity, pressure);
 
       }
 
       }
 
     }
 
     }
 
            
 
            
     <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">measurementsChanged</FONT>() { <FONT COLOR="#000080">notifyObservers</FONT>(); }
+
     public void measurementsChanged() { notifyObservers(); }
 
            
 
            
     <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#800000">float</FONT> temperature, <FONT COLOR="#800000">float</FONT> humidity, <FONT COLOR="#800000">float</FONT> pressure) {
+
     public void setMeasurements(float temperature, float humidity, float pressure) {
       <B>this</B>.<FONT COLOR="#000080">temperature</FONT> = temperature;
+
       _temperature = temperature;
       <B>this</B>.<FONT COLOR="#000080">humidity</FONT>    = humidity;
+
       _humidity        = humidity;
       <B>this</B>.<FONT COLOR="#000080">pressure</FONT>    = pressure;
+
       _pressure      = pressure;
       <FONT COLOR="#000080">measurementsChanged</FONT>();
+
       measurementsChanged();
 
     }
 
     }
 +
 
   }
 
   }
 +
</java5>
  
 
===Dois contextos===
 
===Dois contextos===

Revision as of 12:42, 19 November 2008

O padrão observer permite observar o estado de um objecto. Os observadores registam o seu interesse no estado junto do objecto; quando o estado do objecto muda, os observadores são notificados.

Estrutura

Diagrama de classes

O padrão observer tem a seguinte estrutura de classes:

Observer-dpcd.png

Diagrama de sequência

As colaborações entre os intervenientes são as que figuram no seguinte diagrama de sequência:

Observer-dpsd.png

Exemplo

Observadores e Observados

 public interface Subject {
   public void registerObserver(Observer o);
   public void removeObserver(Observer o);
   public void notifyObservers();
 }
 public interface Observer {
   public void update(float temp, float humidity, float pressure);
 }

Apresentação

Esta interface define o método básico para apresentação de dados.

 public interface DisplayElement {
   public void display();
 }

As implementações da interface de apresentação, que implementam também a de observação, definem várias formas de exibição de dados.

 public class CurrentConditionsDisplay implements Observer, DisplayElement {
   private float temperature;
   private float humidity;
   private Subject weatherData;
       
   public CurrentConditionsDisplay(Subject weatherData) {
     this.weatherData = weatherData;
     weatherData.registerObserver(this);
   }
       
   public void update(float temperature, float humidity, float pressure) {
     this.temperature = temperature;
     this.humidity    = humidity;
     display();
   }
       
   public void display() {
     System.out.println("Current conditions: " + temperature 
                         + "F degrees and " + humidity + "% humidity");
   }
 }
 public class ForecastDisplay implements Observer, DisplayElement {

   private float currentPressure = 29.92f;  
   private float lastPressure;
   private WeatherData weatherData;

   public ForecastDisplay(WeatherData weatherData) {
     this.weatherData = weatherData;
     weatherData.registerObserver(this);
   }

   public void update(float temp, float humidity, float pressure) {
     lastPressure    = currentPressure;
     currentPressure = pressure;
     display();
   }

   public void display() {
     System.out.print("Forecast: ");
     if (currentPressure > lastPressure) {
       System.out.println("Improving weather on the way!");
     } else if (currentPressure == lastPressure) {
       System.out.println("More of the same");
     } else if (currentPressure < lastPressure) {
       System.out.println("Watch out for cooler, rainy weather");
     }
   }
 }

Representação de dados

Os dados de meteorologia correspondem ao objecto observado.

<java5>

 public class WeatherData implements Subject {
   private ArrayList<Observer> _observers = new ArrayList<Observer>();
   private float _temperature;
   private float _humidity;
   private float _pressure;
        
   public WeatherData() { }
        
   public void registerObserver(Observer o) { _observers.add(o); }
        
   public void removeObserver(Observer o) {
     int i = _observers.indexOf(o);
     if (i >= 0) { _observers.remove(i); }
   }
         
   public void notifyObservers() {
     for (int i = 0; i < _observers.size(); i++) {
       Observer observer = _observers.get(i);
       observer.update(temperature, humidity, pressure);
     }
   }
         
   public void measurementsChanged() { notifyObservers(); }
         
   public void setMeasurements(float temperature, float humidity, float pressure) {
     _temperature = temperature;
     _humidity        = humidity;
     _pressure       = pressure;
     measurementsChanged();
   }
 }

</java5>

Dois contextos

Os dois contextos de utilização correspondem a duas estações meteorológicas: em cada uma são utilizados observadores diferentes sobre os mesmos dados.

 public class WeatherStation {
   public static void main(String[] args) {  
     WeatherData weatherData = new WeatherData();  
         
     CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);  
     StatisticsDisplay     statisticsDisplay = new StatisticsDisplay(weatherData);  
     ForecastDisplay         forecastDisplay = new ForecastDisplay(weatherData);  

     weatherData.setMeasurements(80, 65, 30.4f);  
     weatherData.setMeasurements(82, 70, 29.2f);  
     weatherData.setMeasurements(78, 90, 29.2f);  
   }  
 }  
 public class WeatherStationHeatIndex {
   public static void main(String[] args) {
     WeatherData weatherData = new WeatherData();

     CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
     StatisticsDisplay     statisticsDisplay = new StatisticsDisplay(weatherData);
     ForecastDisplay         forecastDisplay = new ForecastDisplay(weatherData);
     HeatIndexDisplay       heatIndexDisplay = new HeatIndexDisplay(weatherData);

     weatherData.setMeasurements(80, 65, 30.4f);
     weatherData.setMeasurements(82, 70, 29.2f);
     weatherData.setMeasurements(78, 90, 29.2f);
   }
 }