Java Reference
In-Depth Information
}
The subject can register a new observer using the registerObserver method and notify his
observers of a tweet with the notifyObservers method. Let's go ahead and implement the Feed
class:
class Feed implements Subject{
private final List<Observer> observers = new ArrayList<>();
public void registerObserver(Observer o) {
this.observers.add(o);
}
public void notifyObservers(String tweet) {
observers.forEach(o -> o.notify(tweet));
}
}
It's a pretty straightforward implementation: the feed keeps an internal list of observers that it
can then notify when a tweet arrives. You can now create a demo application to wire up the
subject and observers:
Feed f = new Feed();
f.registerObserver(new NYTimes());
f.registerObserver(new Guardian());
f.registerObserver(new LeMonde());
f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
Unsurprisingly, The Guardian will pick up this tweet!
Using lambda expressions
You may be wondering how lambda expressions are useful with the observer design pattern.
Notice that the different classes implementing the Observer interface are all providing
implementation for a single method: notify. They're all just wrapping a piece of behavior to
execute when a tweet arrives! Lambda expressions are designed specifically to remove that
boilerplate. Instead of instantiating three observer objects explicitly, you can pass a lambda
expression directly to represent the behavior to execute:
 
Search WWH ::




Custom Search