Java Reference
In-Depth Information
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 different
action for each different 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 another 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);
}
}
}
You're still missing the crucial part: the subject! Let's define an interface for him:
interface Subject{
void registerObserver(Observer o);
void notifyObservers(String tweet);
 
Search WWH ::




Custom Search