Java Reference
In-Depth Information
Subject
+observerCollection
+registerObserver (observer)
+unregisterObserver (observer)
+notifyObservers ( )
Observer
+notify ( )
notifyObservers ( )
for observer in observerCollection
call observer, notify ( )
ConcreteObserverA
ConcreteObserverB
+notify ( )
+notify ( )
FIGURE 11-1: Class diagram of the observer pattern
IMPLEMENTING THE OBSERVER PATTERN IN PLAIN CODE
Java provides an out‐of‐the‐box implementation of the observer pattern. By implementing the
Observer interface and extending the Observable class, developers can easily implement the
observer pattern.
The i rst thing you need to do is create a class that extends the Observable class. In Listing 11‐1,
a news agency informs several types of subscribers when a new story is published. The subscriber
may introduce its own behavior after receiving an update. Listing 11‐2 provides an interface for
publishing the observable class.
LISTING: 11‐1: The news agency implementing the observable interface
package com.devchronicles.observer;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class NewsAgency extends Observable implements Publisher {
private List<Observer> channels = new ArrayList<>();
public void addNews(String newsItem) {
notifyObservers(newsItem);
}
public void notifyObservers(String newsItem) {
for (Observer outlet : this.channels) {
outlet.update(this, newsItem);
}
 
Search WWH ::




Custom Search