|
| 1 | +--- |
| 2 | +title: Observer |
| 3 | +category: Behavioral |
| 4 | +language: it |
| 5 | +tag: |
| 6 | + - Gang Of Four |
| 7 | + - Reactive |
| 8 | +--- |
| 9 | + |
| 10 | +## Anche conosciuto come |
| 11 | + |
| 12 | +Dependents, Publish-Subscribe |
| 13 | + |
| 14 | +## Intento |
| 15 | + |
| 16 | +Stabilire una dipendenza uno-a-molti tra gli oggetti in modo che quando un oggetto cambia stato, tutti i suoi dipendenti vengano avvisati e aggiornati automaticamente. |
| 17 | + |
| 18 | +## Spiegazione |
| 19 | + |
| 20 | +Esempio del mondo reale |
| 21 | + |
| 22 | +> In una terra lontana vivono le razze degli hobbit e degli orchi. Entrambi trascorrono la maggior parte del tempo all'aperto, quindi |
| 23 | +> seguono attentamente i cambiamenti del tempo. Si potrebbe dire che osservano costantemente le |
| 24 | +> condizioni meteorologiche. |
| 25 | +
|
| 26 | +In parole semplici |
| 27 | + |
| 28 | +> Registrarsi come osservatore per ricevere notifiche di cambiamenti di stato nell'oggetto. |
| 29 | +
|
| 30 | +Wikipedia dice |
| 31 | + |
| 32 | +> Il pattern observer è un design pattern in cui un oggetto, chiamato soggetto, |
| 33 | +> mantiene una lista dei suoi dipendenti, chiamati osservatori, e li avvisa automaticamente di eventuali cambiamenti di stato, |
| 34 | +> di solito chiamando uno dei loro metodi. _(Testo tradotto dalla voce Observer Pattern da Wikipedia in lingua inglese)._ |
| 35 | +
|
| 36 | +**Esempio di codice** |
| 37 | + |
| 38 | +Iniziamo introducendo l'interfaccia `WeatherObserver` e le nostre razze, `Orcs` e `Hobbits`. |
| 39 | + |
| 40 | +```java |
| 41 | +public interface WeatherObserver { |
| 42 | + |
| 43 | + void update(WeatherType currentWeather); |
| 44 | +} |
| 45 | + |
| 46 | +@Slf4j |
| 47 | +public class Orcs implements WeatherObserver { |
| 48 | + |
| 49 | + @Override |
| 50 | + public void update(WeatherType currentWeather) { |
| 51 | + LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +@Slf4j |
| 56 | +public class Hobbits implements WeatherObserver { |
| 57 | + |
| 58 | + @Override |
| 59 | + public void update(WeatherType currentWeather) { |
| 60 | + switch (currentWeather) { |
| 61 | + LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now"); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +Poi c'è il `Weather` che cambia continuamente. |
| 68 | + |
| 69 | +```java |
| 70 | +@Slf4j |
| 71 | +public class Weather { |
| 72 | + |
| 73 | + private WeatherType currentWeather; |
| 74 | + private final List<WeatherObserver> observers; |
| 75 | + |
| 76 | + public Weather() { |
| 77 | + observers = new ArrayList<>(); |
| 78 | + currentWeather = WeatherType.SUNNY; |
| 79 | + } |
| 80 | + |
| 81 | + public void addObserver(WeatherObserver obs) { |
| 82 | + observers.add(obs); |
| 83 | + } |
| 84 | + |
| 85 | + public void removeObserver(WeatherObserver obs) { |
| 86 | + observers.remove(obs); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Makes time pass for weather. |
| 91 | + */ |
| 92 | + public void timePasses() { |
| 93 | + var enumValues = WeatherType.values(); |
| 94 | + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; |
| 95 | + LOGGER.info("The weather changed to {}.", currentWeather); |
| 96 | + notifyObservers(); |
| 97 | + } |
| 98 | + |
| 99 | + private void notifyObservers() { |
| 100 | + for (var obs : observers) { |
| 101 | + obs.update(currentWeather); |
| 102 | + } |
| 103 | + } |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +Ecco l'esempio completo in azione. |
| 108 | + |
| 109 | +```java |
| 110 | + var weather = new Weather(); |
| 111 | + weather.addObserver(new Orcs()); |
| 112 | + weather.addObserver(new Hobbits()); |
| 113 | + weather.timePasses(); |
| 114 | + weather.timePasses(); |
| 115 | + weather.timePasses(); |
| 116 | + weather.timePasses(); |
| 117 | +``` |
| 118 | + |
| 119 | +Output del programma: |
| 120 | + |
| 121 | +``` |
| 122 | +The weather changed to rainy. |
| 123 | +The orcs are facing rainy weather now |
| 124 | +The hobbits are facing rainy weather now |
| 125 | +The weather changed to windy. |
| 126 | +The orcs are facing windy weather now |
| 127 | +The hobbits are facing windy weather now |
| 128 | +The weather changed to cold. |
| 129 | +The orcs are facing cold weather now |
| 130 | +The hobbits are facing cold weather now |
| 131 | +The weather changed to sunny. |
| 132 | +The orcs are facing sunny weather now |
| 133 | +The hobbits are facing sunny weather now |
| 134 | +``` |
| 135 | + |
| 136 | +## Diagramma delle classi |
| 137 | + |
| 138 | + |
| 139 | + |
| 140 | +## Applicabilità |
| 141 | + |
| 142 | +Usa il pattern Observer in una qualsiasi delle seguenti situazioni: |
| 143 | + |
| 144 | +* Quando un'astrazione ha due aspetti, uno dipendente dall'altro. L'incapsulamento di questi aspetti in oggetti separati ti permette di variarli e riutilizzarli in modo indipendente. |
| 145 | +* Quando una modifica a un oggetto richiede la modifica di altri oggetti, e non sai quanti oggetti devono essere modificati. |
| 146 | +* Quando un oggetto dovrebbe essere in grado di avvisare altri oggetti senza fare presupposizioni su chi siano questi oggetti. In altre parole, non desideri che questi oggetti siano strettamente accoppiati. |
| 147 | + |
| 148 | +## Usi noti |
| 149 | + |
| 150 | +* [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) |
| 151 | +* [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) |
| 152 | +* [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) |
| 153 | +* [RxJava](https://github.com/ReactiveX/RxJava) |
| 154 | + |
| 155 | +## Collegamenti esterni |
| 156 | + |
| 157 | +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) |
| 158 | +* [Java Generics and Collections](https://www.amazon.com/gp/product/0596527756/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596527756&linkCode=as2&tag=javadesignpat-20&linkId=246e5e2c26fe1c3ada6a70b15afcb195) |
| 159 | +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) |
| 160 | +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) |
0 commit comments