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

From Wiki**3

 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{{NAVPO}}
 
{{TOCright}}
 
{{TOCright}}
<!--Material correspondente à aula 28.-->
+
 
 
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.
 
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.
  
Line 11: Line 12:
 
[[Image:observer-dpcd.png|600px]]
 
[[Image:observer-dpcd.png|600px]]
  
===Diagrama de sequência===
+
===Diagrama de sequência===
  
As colaborações entre os intervenientes são as que figuram no seguinte diagrama de sequência:
+
As colaborações entre os intervenientes são as que figuram no seguinte diagrama de sequência:
  
 
[[Image:observer-dpsd.png|500px]]
 
[[Image:observer-dpsd.png|500px]]
Line 19: Line 20:
 
==Exemplo==
 
==Exemplo==
  
===Observadores e Observados===
+
* [[Observer (padrão de desenho)/Exemplo 01: Estação Meteorológica|Exemplo 01: Estação Meteorológica]]
 
 
  <B>public</B> <B>interface</B> Subject {
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">registerObserver</FONT>(Observer o);
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">removeObserver</FONT>(Observer o);
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">notifyObservers</FONT>();
 
  }
 
 
 
  <B>public</B> <B>interface</B> Observer {
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">update</FONT>(<FONT COLOR="#800000">float</FONT> temp, <FONT COLOR="#800000">float</FONT> humidity, <FONT COLOR="#800000">float</FONT> pressure);
 
  }
 
 
 
===Apresentação===
 
 
 
Esta interface define o método básico para apresentação de dados.
 
 
 
  <B>public</B> <B>interface</B> DisplayElement {
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">display</FONT>();
 
  }
 
 
 
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.
 
 
 
  <B>public</B> <B>class</B> CurrentConditionsDisplay <B>implements</B> Observer, DisplayElement {
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> temperature;
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> humidity;
 
    <B>private</B> Subject weatherData;
 
       
 
    <B>public</B> <FONT COLOR="#000080">CurrentConditionsDisplay</FONT>(Subject weatherData) {
 
      <B>this</B>.<FONT COLOR="#000080">weatherData</FONT> = weatherData;
 
      weatherData.<FONT COLOR="#000080">registerObserver</FONT>(<B>this</B>);
 
    }
 
       
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">update</FONT>(<FONT COLOR="#800000">float</FONT> temperature, <FONT COLOR="#800000">float</FONT> humidity, <FONT COLOR="#800000">float</FONT> pressure) {
 
      <B>this</B>.<FONT COLOR="#000080">temperature</FONT> = temperature;
 
      <B>this</B>.<FONT COLOR="#000080">humidity</FONT>    = humidity;
 
      <FONT COLOR="#000080">display</FONT>();
 
    }
 
       
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">display</FONT>() {
 
      <B><FONT COLOR="#0095ff">System</FONT></B>.<FONT COLOR="#000080">out</FONT>.<FONT COLOR="#000080">println</FONT>(<FONT COLOR="#dd0000">&quot;Current conditions: &quot;</FONT> + temperature
 
                          + <FONT COLOR="#dd0000">&quot;F degrees and &quot;</FONT> + humidity + <FONT COLOR="#dd0000">&quot;% humidity&quot;</FONT>);
 
    }
 
  }
 
 
 
  <B>public</B> <B>class</B> ForecastDisplay <B>implements</B> Observer, DisplayElement {
 
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> currentPressure = <FONT COLOR="#800080">29.92f</FONT>; 
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> lastPressure;
 
    <B>private</B> WeatherData weatherData;
 
 
    <B>public</B> <FONT COLOR="#000080">ForecastDisplay</FONT>(WeatherData weatherData) {
 
      <B>this</B>.<FONT COLOR="#000080">weatherData</FONT> = weatherData;
 
      weatherData.<FONT COLOR="#000080">registerObserver</FONT>(<B>this</B>);
 
    }
 
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">update</FONT>(<FONT COLOR="#800000">float</FONT> temp, <FONT COLOR="#800000">float</FONT> humidity, <FONT COLOR="#800000">float</FONT> pressure) {
 
      lastPressure    = currentPressure;
 
      currentPressure = pressure;
 
      <FONT COLOR="#000080">display</FONT>();
 
    }
 
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">display</FONT>() {
 
      <B><FONT COLOR="#0095ff">System</FONT></B>.<FONT COLOR="#000080">out</FONT>.<FONT COLOR="#000080">print</FONT>(<FONT COLOR="#dd0000">&quot;Forecast: &quot;</FONT>);
 
      <B>if</B> (currentPressure &gt; lastPressure) {
 
        <B><FONT COLOR="#0095ff">System</FONT></B>.<FONT COLOR="#000080">out</FONT>.<FONT COLOR="#000080">println</FONT>(<FONT COLOR="#dd0000">&quot;Improving weather on the way!&quot;</FONT>);
 
      } <B>else</B> <B>if</B> (currentPressure == lastPressure) {
 
        <B><FONT COLOR="#0095ff">System</FONT></B>.<FONT COLOR="#000080">out</FONT>.<FONT COLOR="#000080">println</FONT>(<FONT COLOR="#dd0000">&quot;More of the same&quot;</FONT>);
 
      } <B>else</B> <B>if</B> (currentPressure &lt; lastPressure) {
 
        <B><FONT COLOR="#0095ff">System</FONT></B>.<FONT COLOR="#000080">out</FONT>.<FONT COLOR="#000080">println</FONT>(<FONT COLOR="#dd0000">&quot;Watch out for cooler, rainy weather&quot;</FONT>);
 
      }
 
    }
 
  }
 
 
 
===Representação de dados===
 
 
 
Os dados de meteorologia correspondem ao objecto observado.
 
 
 
  <B>public</B> <B>class</B> WeatherData <B>implements</B> Subject {
 
    <B>private</B> <B><FONT COLOR="#0095ff">ArrayList</FONT></B> observers;
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> temperature;
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> humidity;
 
    <B>private</B> <FONT COLOR="#800000">float</FONT> pressure;
 
       
 
    <B>public</B> <FONT COLOR="#000080">WeatherData</FONT>() { observers = <B>new</B> <B><FONT COLOR="#0095ff">ArrayList</FONT></B>(); }
 
       
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">registerObserver</FONT>(Observer o) { observers.<FONT COLOR="#000080">add</FONT>(o); }
 
       
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">removeObserver</FONT>(Observer o) {
 
      <FONT COLOR="#800000">int</FONT> i = observers.<FONT COLOR="#000080">indexOf</FONT>(o);
 
      <B>if</B> (i &gt;= <FONT COLOR="#0000ff">0</FONT>) { observers.<FONT COLOR="#000080">remove</FONT>(i); }
 
    }
 
         
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">notifyObservers</FONT>() {
 
      <B>for</B> (<FONT COLOR="#800000">int</FONT> i = <FONT COLOR="#0000ff">0</FONT>; i &lt; observers.<FONT COLOR="#000080">size</FONT>(); i++) {
 
        Observer observer = (Observer)observers.<FONT COLOR="#000080">get</FONT>(i);
 
        observer.<FONT COLOR="#000080">update</FONT>(temperature, humidity, pressure);
 
      }
 
    }
 
         
 
    <B>public</B> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">measurementsChanged</FONT>() { <FONT COLOR="#000080">notifyObservers</FONT>(); }
 
         
 
    <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) {
 
      <B>this</B>.<FONT COLOR="#000080">temperature</FONT> = temperature;
 
      <B>this</B>.<FONT COLOR="#000080">humidity</FONT>    = humidity;
 
      <B>this</B>.<FONT COLOR="#000080">pressure</FONT>    = pressure;
 
      <FONT COLOR="#000080">measurementsChanged</FONT>();
 
    }
 
  }
 
 
 
===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.
 
 
 
  <B>public</B> <B>class</B> WeatherStation {
 
    <B>public</B> <FONT COLOR="#800000">static</FONT> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">main</FONT>(<B><FONT COLOR="#0095ff">String</FONT></B>[] args) { 
 
      WeatherData weatherData = <B>new</B> <FONT COLOR="#000080">WeatherData</FONT>(); 
 
         
 
      CurrentConditionsDisplay currentDisplay = <B>new</B> <FONT COLOR="#000080">CurrentConditionsDisplay</FONT>(weatherData); 
 
      StatisticsDisplay    statisticsDisplay = <B>new</B> <FONT COLOR="#000080">StatisticsDisplay</FONT>(weatherData); 
 
      ForecastDisplay        forecastDisplay = <B>new</B> <FONT COLOR="#000080">ForecastDisplay</FONT>(weatherData); 
 
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">80</FONT>, <FONT COLOR="#0000ff">65</FONT>, <FONT COLOR="#800080">30.4f</FONT>); 
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">82</FONT>, <FONT COLOR="#0000ff">70</FONT>, <FONT COLOR="#800080">29.2f</FONT>); 
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">78</FONT>, <FONT COLOR="#0000ff">90</FONT>, <FONT COLOR="#800080">29.2f</FONT>); 
 
    } 
 
  } 
 
 
 
  <B>public</B> <B>class</B> WeatherStationHeatIndex {
 
    <B>public</B> <FONT COLOR="#800000">static</FONT> <FONT COLOR="#800000">void</FONT> <FONT COLOR="#000080">main</FONT>(<B><FONT COLOR="#0095ff">String</FONT></B>[] args) {
 
      WeatherData weatherData = <B>new</B> <FONT COLOR="#000080">WeatherData</FONT>();
 
 
      CurrentConditionsDisplay currentDisplay = <B>new</B> <FONT COLOR="#000080">CurrentConditionsDisplay</FONT>(weatherData);
 
      StatisticsDisplay    statisticsDisplay = <B>new</B> <FONT COLOR="#000080">StatisticsDisplay</FONT>(weatherData);
 
      ForecastDisplay        forecastDisplay = <B>new</B> <FONT COLOR="#000080">ForecastDisplay</FONT>(weatherData);
 
      HeatIndexDisplay      heatIndexDisplay = <B>new</B> <FONT COLOR="#000080">HeatIndexDisplay</FONT>(weatherData);
 
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">80</FONT>, <FONT COLOR="#0000ff">65</FONT>, <FONT COLOR="#800080">30.4f</FONT>);
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">82</FONT>, <FONT COLOR="#0000ff">70</FONT>, <FONT COLOR="#800080">29.2f</FONT>);
 
      weatherData.<FONT COLOR="#000080">setMeasurements</FONT>(<FONT COLOR="#0000ff">78</FONT>, <FONT COLOR="#0000ff">90</FONT>, <FONT COLOR="#800080">29.2f</FONT>);
 
    }
 
  }
 
  
[[category:OOP]]
+
[[category:Ensino]]
[[category:Teaching]]
+
[[category:PO]]

Latest revision as of 14:03, 19 November 2015

Programação com Objectos
Introduction
Creation and Destruction
Inheritance & Composition
Abstraction & Polymorphism
Code Organization
Java Topics
Inner Classes
Enumerations
Data Structures
Exceptions
Input/Output
RTTI
Other Topics
JUnit Tests
UML Topics
Design Patterns
"Simple" Factory
Composite & Visitor
Command
Strategy & State
Template Method
Observer
Abstract Factory
Decorator & Adapter
Façade (aka Facade)

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