Java Reference
In-Depth Information
}
public void register(Observer outlet) {
channels.add(outlet);
}
}
LISTING: 11‐2: The Publisher interface
package com.devchronicles.observer;
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
package com.devchronicles.observer;
import java.util.Observable;
import java.util.Observer;
public class RadioChannel implements Observer {
@Override
public void update(Observable agency, Object newsItem) {
if (agency instanceof Publisher) {
System.out.println((String)newsItem);
}
}
}
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
newsAgency.register(radioChannel);
// 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