Java Magazine, Nov/Dec 2016
Observer notify Subject notifyObserver ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 58 new to java Observer Pattern The observer design pattern is a common solution when an object called the subject needs to automatically notify a list of other objects called observers that some event has occurred for example a state change You typically come across this pattern when working with GUI applications You register a set of observers on a GUI component such as a button If the button is clicked the observers are notified and can execute a specific action But the observer pattern isnt limited to GUIs For example the observer design pattern is also suitable in a situation where several traders observers might wish to react to the change of price of a stock subject Figure 2 illustrates the UML diagram of the observer pattern Lets write some code to see how the observer pattern is useful in practice Youll design and implement a customized notification system for an application like Twitter The concept is simple several newspaper agencies The New York Times The Guardian and Le Monde are subscribed to a feed of news tweets and may want to receive a notification if a tweet contains a particular keyword First you need an Observer interface that groups the different observers It has just one method called notify that will be called by the subject Feed when a new tweet is available interface Observer void notify String tweet You can now declare different observers here the three newspapers that produce a diferent action for each diferent keyword contained in a tweet class NYTimes implements Observer public void notify String tweet if tweet null tweet contains money System out println Breaking news in NY tweet class Guardian implements Observer public void notify String tweet if tweet null tweet contains queen System out println Yet more news in London tweet class LeMonde implements Observer public void notify String tweet if tweet null tweet contains wine System out println Today cheese wine and news tweet Youre still missing the crucial part the subject Lets define an interface for it interface Subject void registerObserver Observer o void notifyObservers String tweet ConcreteObserverB ConcreteObserverA Figure 2 The observer design pattern
You must have JavaScript enabled to view digital editions.