One-to-many dependency: when one object changes, all its dependents are updated automatically.
aka Event Subscriber, Listener
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
Problem

Magazine and newspaper subscriptions.
If you subscribe to a newspaper or magazine, you no longer need to go to the store to check if the next issue is available. Instead, the publisher sends new issues directly to your mailbox right after publication or even in advance.
The publisher maintains a list of subscribers and knows which magazines they’re interested in. Subscribers can leave the list at any time when they wish to stop the publisher sending new magazine issues to them.
Structure

When to Use
- When you have one-to-many dependencies between objects.
- When you want to decouple the subject from the observers (they only communicate via interfaces).
- When you need a notification mechanism for state changes.
Real World Examples
- Event listeners in GUIs (button clicks, keypresses).
- Social media (followers getting updates).
- Stock price updates to subscribed clients.
- Publish-subscribe messaging systems.
Code Examples
import java.util.ArrayList;
import java.util.List;
// Observer interface
interface Observer {
void update(String news);
}
// Subject interface
interface Subject {
void addObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
// Concrete Subject
class NewsAgency implements Subject {
private List<Observer> observers = new ArrayList<>();
private String news;
public void setNews(String news) {
this.news = news;
notifyObservers();
}
public void addObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
observers.remove(o);
}
public void notifyObservers() {
for (Observer o : observers) {
o.update(news);
}
}
}
// Concrete Observer
class NewsChannel implements Observer {
private String name;
public NewsChannel(String name) {
this.name = name;
}
public void update(String news) {
System.out.println(name + " received news: " + news);
}
}
// Main class to run the demo
public class ObserverPatternDemo {
public static void main(String[] args) {
NewsAgency agency = new NewsAgency();
NewsChannel channel1 = new NewsChannel("Channel One");
NewsChannel channel2 = new NewsChannel("Channel Two");
agency.addObserver(channel1);
agency.addObserver(channel2);
agency.setNews("Breaking News: Observer Pattern Explained!");
agency.removeObserver(channel1);
agency.setNews("Update: Channel One has unsubscribed.");
}
}