Observer Pattern

  • Used to have one to many relationships
  • allows loose coupling between Publisher which is creating events and subscribers which are listening to the events
  • Examples:
    • java.util.Observer
    • java.util.EventListener
    • RxJava
  • Reactor pattern is specific case of Observer Pattern

Implementation

  • We can also include eventName to make it more general
  • We can make Observable interface for NewsAgency to make it more general
interface Channel {
    void update(String news);
}
 
class NewsChannel implements Channel {
    private String news;
    private String channelName;
    NewsChannel(String channelName) {
        this.channelName = channelName;
    }
 
    @Override
    public void update(String news) {
        this.news = this.channelName + ": " + news;
    }
 
    public String getNews() {
        return this.news;
    }
}
 
class NewsAgency { 
    private List<Channel> channels = new ArrayList<>();
 
    public void subscribe(Channel channel) {
        this.channels.add(channel);
    }
 
    public void unsubscribe(Channel channel) {
        this.channels.remove(channel);
    }
 
    public void updateNews(String news) {
        for (Channel channel : this.channels) {
            channel.update(news);
        }
    }
}
  • Driver
public class Test {
    public static void main(String[] args) {
        var newsAgency = new NewsAgency();
        var newsChannel1 = new NewsChannel("AajTak");
        var newsChannel2 = new NewsChannel("NDTV");
        newsAgency.subscribe(newsChannel1);
        newsAgency.subscribe(newsChannel2);
        newsAgency.updateNews("Chandrayan 3 landed successfully");
        System.out.println(newsChannel1.getNews());
        System.out.println(newsChannel2.getNews());
        // AajTak: Chandrayan 3 landed successfully
        // NDTV: Chandrayan 3 landed successfully
        newsAgency.unsubscribe(newsChannel2);
        newsAgency.updateNews("Cold waves will hit");
        System.out.println(newsChannel1.getNews());
        System.out.println(newsChannel2.getNews()); // not updated
        // AajTak: Cold waves will hit
        // NDTV: Chandrayan 3 landed successfully
	}
}

UML

Observer_Pattern_UML