As we saw above, the journalist is currently managing how all the content, including the headline, text, picture, and summary, is being distributed between the channels.
To convert this scenario into code, imagine a Journalist-class, which have an instance of the TelevisionNews, Newspaper, and OnlinePublisher. For the journalist to provide each of the observers with the desired content, the journalist must call each of the observers’ publish()-method individually and provide their desired content as arguments. Sounds like a lot of responsibilities for a journalist.
Additionally, with this code structure, it will not be possible for the journalist to change observers at runtime. Since the journalist does not have a common method of publishing their article it will not be possible to make a simple way of adding new observers. They are therefore restricted to selecting their observers at compile time. Something has to change, so let’s see what the observer pattern can do for us.
class Journalist {
TelevisionNews televisionNews;
Newspaper newspaper;
OnlinePublisher onlinePublisher;
public Journalist() {
televisionNews = new TelevisionNews();
newspaper = new Newspaper();
onlinePublisher = new OnlinePublisher();
}
void publish(String title, String summary, String image, String text){
televisionNews.publish(headline, picture);
newspaper.publish(headline, text, picture, summary);
onlinePublisher.publish(headline, picture, summary);
}
}