Java Reference
In-Depth Information
public void register(Observer outlet) {
LISTING: 11‐2: The Publisher interface
public interface Publisher {}
Next, you need to create the class that observes the NewsAgency for changes. This observer must
implement the Observer interface as in Listing 11‐3.
LISTING: 11‐3: Concrete observer
import java.util.Observable;
import java.util.Observer;
public class RadioChannel implements Observer {
public void update(Observable agency, Object newsItem) {
if (agency instanceof Publisher) {
Finally, you must register the RadioChannel observer with the NewsAgency observable and create
some news.
// Create the observer and subject
NewsAgency newsAgency = new NewsAgency();
RadioChannel radioChannel = new RadioChannel();
// Register the observer with the subject
// Now add some news headlines
newsAgency.addNews("Breaking news: Life f ound on Mars");
newsAgency.addNews("Update: Earth invasion imminent");
newsAgency.addNews("Just in: Hail to our new Martian overlords");
The output in the console should be as follows:
Breaking news: Life f ound on Mars
Update: Earth invasion imminent
Just in: Hail to our new Martian overlords
Search WWH ::

Custom Search