Observer Pattern in Java: Explanation & Practice

Implement the observer design pattern

Problem summary

Create a NewsAgency (subject) that notifies NewsChannel observers when news is published.

Starter code

interface Observer {
    void update(String news);
}

// Implement NewsAgency and NewsChannel

public class Main {
    public static void main(String[] args) {
        NewsAgency agency = new NewsAgency();
        NewsChannel channel1 = new NewsChannel("CNN");
        NewsChannel channel2 = new NewsChannel("BBC");
        
        agency.subscribe(channel1);
        agency.subscribe(channel2);
        
        agency.publishNews("Breaking news!");
    }
}

Expected output and test cases

  • All observers notified
    CNN received: Breaking news!
    BBC received: Breaking news!

Hints

  1. Subject maintains list of observers
  2. subscribe/unsubscribe methods
  3. publishNews iterates and calls update on each

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler