We are going to describe the Observer design pattern.
The Observer pattern is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects (observers) about any events that happen to the object (subject) they're observing.
Key components:
Subject (or Observable): The object that holds the state and notifies observers when its state changes.
Observer: An interface that defines the update method, which is called by the subject when the subject's state changes.
ConcreteSubject: A concrete implementation of the Subject that stores the state of interest and notifies observers when the state changes.
ConcreteObserver: Implements the Observer interface and stores a reference to the ConcreteSubject. It updates its state to stay consistent with the subject's state.
How it works:
The ConcreteSubject maintains a list of observers (typically through the Observer interface).
When the state of the ConcreteSubject changes, it iterates over the list of observers and calls their update method.
The ConcreteObserver, upon being notified, can query the subject for its new state and update itself accordingly.
Benefits:
Loose coupling: The subject and observers are loosely coupled. The subject knows only the Observer interface, not the concrete classes.
Dynamic relationships: Observers can be added or removed at runtime.
Drawbacks:
If not managed well, the update chain can become complex and lead to performance issues (e.g., many observers and frequent updates).
The order of notification is not guaranteed (unless you specifically implement ordering).
Example use cases:
Implementing distributed event handling systems.
Model-View-Controller (MVC) pattern: The model is the subject, and views are observers.
Event handling in many programming frameworks.
Let's write a simple example in Java-like pseudocode to illustrate:
Step 1: Define the Observer interface.
Step 2: Define the Subject interface (or abstract class) with methods to attach, detach, and notify observers.
Step 3: Implement the ConcreteSubject that extends the Subject and has a state that, when changed, notifies observers.
Step 4: Implement ConcreteObserver that implements the Observer interface and updates its state based on the subject.
However, note that in some implementations, the Subject might be an abstract class, and the ConcreteSubject extends it and overrides the state change method to call notifyObservers.
Alternatively, we can have a single Subject class that is used by ConcreteSubject via composition (if we use an interface for Subject).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
public ConcreteObserver(String name, ConcreteSubject subject) {
this.name = name;
this.subject = subject;
subject.attach(this);
}
@Override
public void update(String message) {
System.out.println(name + " received update: " + message);
}
// Optionally, we can have a method to detach this observer from the subject.
}
But note: In the above, the ConcreteObserver is tightly coupled to ConcreteSubject because it uses the ConcreteSubject's state.
Alternatively, we can make the update method more generic by having the subject pass itself as an argument, so the observer can call getState().
@Override
public void update(Subject subject) {
if (subject instanceof ConcreteSubject) {
String state = ((ConcreteSubject) subject).getState();
System.out.println(name + " received update: " + state);
}
}
However, this introduces a dependency on ConcreteSubject in the observer, which breaks the pattern's intent of loose coupling.
Alternatively, we can have the subject pass the state as an argument (as in the first example) or have the observer pull the state from the subject via an interface.
Let's define the Subject interface to have a method to get the state? But that might not be general.
Another approach: The update method in Observer can take the subject and the observer can call a method on the subject to get the relevant data, but that requires the subject to expose the data via an interface.
So, we can have:
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
// Optionally, we can have a method to get the state of interest, but that might not be general for all subjects.
}
But then the ConcreteSubject would implement that method. However, the Observer update method would need to know what to get.
Alternatively, we can have the subject pass the changed data as an argument to update. This is the "push" model.
In the "pull" model, the observer is responsible for pulling the data from the subject when it is notified.
We can design the Observer interface to have:
void update(Subject subject); // pull model: the observer gets the subject and then queries it for the data it needs.
Then the ConcreteObserver would have to know what methods to call on the subject. To avoid casting, we can have a generic Subject interface that includes the methods to get the data of interest? But that might not be possible if different subjects have different data.
So, often in practice, the Observer pattern is implemented with the subject passing the changed data (push) or the observer pulling the data (pull) from the subject. The pull model is more flexible because the observer can get exactly what it needs, but it requires the subject to expose that data through an interface.
Given the complexity, let's stick with the push model for simplicity in the example, but note that the pull model is also common.
However, note that in the first example we passed the state (string) as an argument. That is push. But then the observer doesn't need to know about the subject.
So, which one to choose?
If the subject has a lot of state and different observers are interested in different parts, push might send too much data or too little. Then pull is better because the observer can get exactly what it needs.
If the subject's state is small and all observers are interested in the same data, push is simpler.
Let me adjust the example to use the pull model without breaking the interface:
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
// We don't put getState here because not all subjects have the same state.
}
Then in ConcreteSubject, we have:
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(this);
}
}
And in ConcreteObserver:
@Override
public void update(Subject subject) {
if (subject instanceof ConcreteSubject) {
ConcreteSubject concreteSubject = (ConcreteSubject) subject;
String state = concreteSubject.getState();
// do something with state
}
}
But then the ConcreteObserver is coupled to ConcreteSubject. To avoid that, we can have an interface for the state we are interested in:
interface StatefulSubject {
String getState();
}
Then ConcreteSubject implements StatefulSubject.
And in ConcreteObserver:
@Override
public void update(Subject subject) {
if (subject instanceof StatefulSubject) {
String state = ((StatefulSubject) subject).getState();
// ...
}
}
This way, the observer only depends on the StatefulSubject interface, not the ConcreteSubject.
However, if we have multiple types of state, we might need multiple interfaces.
Alternatively, we can have the subject pass the state as an argument (push) and avoid the need for the observer to know about the subject's type.
Given the above, the pattern can be implemented in two ways:
Push: The subject sends the changed data to the observers. The update method in Observer takes the data as an argument.
Pull: The subject sends itself (or a reference) to the observers, and the observers pull the data they need.
Which one is better? It depends on the use case.
In the classic GoF book, they use the pull model: the update method in Observer has no arguments, and the observer is expected to query the subject for the data. But they also mention that sometimes it's better to pass the data as an argument.
So they use the pull model: the Update method takes the subject as an argument.
But note: the Observer interface does not define how to get the state. It's up to the concrete observer to know what to get from the subject.
So, to summarize:
The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The subject and observers are loosely coupled: the subject knows only that it has a list of observers that implement the Observer interface, and the observers know that they are observing a subject (but not necessarily the concrete class).
Let's write the example in the pull model as per GoF:
class ConcreteSubject implements Subject {
private List observers = new ArrayList<>();
private int state;
public void setState(int state) {
this.state = state;
notifyObservers();
}
public int getState() {
return state;
}
// implement attach, detach, notifyObservers as above, but in notifyObservers call observer.update(this)
public ConcreteObserver(String name, ConcreteSubject subject) {
this.name = name;
this.subject = subject;
subject.attach(this);
}
@Override
public void update(Subject subject) {
if (subject == this.subject) {
int state = ((ConcreteSubject) subject).getState();
System.out.println(name + " received update: state = " + state);
}
}
}
But note: the ConcreteObserver is still coupled to ConcreteSubject because of the cast. To avoid that, we can have an interface for the state:
interface Stateful {
int getState();
}
Then ConcreteSubject implements Stateful.
And in ConcreteObserver:
@Override
public void update(Subject subject) {
if (subject instanceof Stateful) {
int state = ((Stateful) subject).getState();
System.out.println(name + " received update: state = " + state);
}
}
Now the ConcreteObserver only depends on the Stateful interface, not the ConcreteSubject.
However, note that the subject passed to update is of type Subject, and we are checking if it is Stateful. This is safe because we know that the subject we are observing is a ConcreteSubject which is Stateful.
But what if we have multiple subjects of different types? Then we might have multiple interfaces.
Alternatively, we can have the observer know about the specific subject it is observing (like in the first example of ConcreteObserver that had a reference to ConcreteSubject). That is also acceptable and common.
In fact, in the GoF example, the ConcreteObserver holds a reference to the ConcreteSubject and in the update method, it uses that reference to get the state. But note that in the update method, they are passed the subject that changed. They can compare to see if it's the one they are interested in.
However, in the example above, we are passing the subject that changed and the observer only updates if it's the subject it's observing. This allows an observer to observe multiple subjects? Actually, the same observer can be attached to multiple subjects, and then in the update method, it can check which subject sent the update.
But in our example, we attached the observer to only one subject. If we attach the same observer to multiple subjects, then we need to handle that.
Given the complexity, for simplicity, we often have one observer per subject.
But the pattern allows multiple subjects and multiple observers.
So, the key is:
The subject maintains a list of observers (by the Observer interface).
When the subject changes, it calls update on every observer, passing itself (or the changed data) as an argument.
The observer then decides what to do with that information.
In the example above, we are passing the subject (pull model). In the first example, we passed the state (push model).
Let me write a version that uses push:
interface Observer {
void update(int state); // or whatever the state type is
}
Then the ConcreteSubject, when notifying, passes the state:
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(state);
}
}
And the ConcreteObserver:
@Override
public void update(int state) {
System.out.println(name + " received update: state = " + state);
}
This is simpler and avoids the cast, but now the observer doesn't know which subject the update came from. If the observer is observing multiple subjects, it cannot distinguish.
So, if an observer is observing multiple subjects and we use push, we might need to include the subject in the update. Then we are back to passing the subject and having the observer pull the state? Or we can pass both:
void update(Subject subject, int state);
But then the subject is passed but the state is already provided. The observer can use the state without querying the subject, but it might still want to query the subject for other data.
Alternatively, we can pass the subject and let the observer pull the state, but then we are in the pull model.
Given the above, the pattern is flexible and can be adapted.
In summary, the Observer pattern is about:
Defining a one-to-many dependency.
When the subject changes, it notifies all its observers.
The subject and observers are loosely coupled.
The exact mechanism (push vs pull) and the details of the update method can vary.
Let's stick to the pull model as in the GoF book for the description.
However, note that in many modern languages and frameworks, the push model is also common (for example, in Java's PropertyChangeListener, the update method is called with the old and new values, which is push).
So, the pattern is defined by the intent and the structure, not the exact mechanism of passing data.
Final description:
The Observer pattern is a design pattern that allows an object, called the subject, to maintain a list of its dependents, called observers, and notify them automatically of any state changes, usually by calling one of their methods.
It is used when:
A change to one object requires changing others, and you don't know how many objects need to change.
An object should be able to notify other objects without making assumptions about who those objects are.
Implementation considerations:
The order of notification is not specified. If order matters, you might need to use a different structure (like a priority queue) or document the order.
The subject should not notify observers in the middle of its state change, because the observers might query the subject and get an inconsistent state. It's better to notify after the state change is complete.
Be cautious of memory leaks: if observers are not detached, they might be kept in the subject's list even when they are no longer needed.
Example in real life:
In a newspaper publishing company (subject), when a new edition is published, it sends (notifies) the new edition to all its subscribers (observers). The subscribers can then read the new edition.
In event-driven programming, an event source (subject) can have multiple event listeners (observers). When the event occurs, the source notifies all listeners.
In MVC, the model is the subject and the views are observers. When the model changes, it notifies the views to update.
That's the Observer pattern.
The Observer design pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When the state of a subject (or observable) changes, all its observers are automatically notified and updated. This enables loose coupling between the subject and its observers.
Key Components
Subject (Observable)
Maintains a list of observers.
Provides methods to attach, detach, and notify observers.
Holds the state that observers are interested in.
Observer
Defines an update interface (e.g., update()) that subjects call when they change.
Concrete observers implement this interface to react to state changes.
ConcreteSubject
Extends/implements the Subject.
Stores the actual state of interest.
Calls notifyObservers() when its state changes.
ConcreteObserver
Implements the Observer interface.
Keeps a reference to the ConcreteSubject (optional) to fetch updated state.
Implements the update() method to react to changes (e.g., refresh UI, recalculate data).
How It Works
Registration: Observers register themselves with the subject via attach().
State Change: The subject modifies its state.
Notification: Subject calls notifyObservers(), which invokes update() on each registered observer.
Update: Each observer fetches new data from the subject (if needed) and updates itself.
Example (Pseudo-Code)
// Observer Interface
interface Observer {
void update(String message);
}
// Subject Interface
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
// ConcreteSubject
class NewsAgency implements Subject {
private List<Observer> observers = new ArrayList<>();
private String breakingNews;
public void setNews(String news) {
this.breakingNews = news;
notifyObservers();
}
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(breakingNews);
}
}
}
// ConcreteObserver
class SMSSubscriber implements Observer {
private String name;
public SMSSubscriber(String name) {
this.name = name;
}
@Override
public void update(String news) {
System.out.println(name + " received SMS: " + news);
}
}
// Usage
public class Main {
public static void main(String[] args) {
NewsAgency agency = new NewsAgency();
Observer sms1 = new SMSSubscriber("Alice");
Observer sms2 = new SMSSubscriber("Bob");
agency.attach(sms1);
agency.attach(sms2);
agency.setNews("Breaking: Observer Pattern Decoded!");
// Output:
// Alice received SMS: Breaking: Observer Pattern Decoded!
// Bob received SMS: Breaking: Observer Pattern Decoded!
}
}
Variants
Push vs. Pull Models
Push: Subject passes changed data directly in update() (as in the example).
Pull: Subject passes itself as an argument; observers query the subject for data (more flexible but increases coupling).
Event Bus / Publish-Subscribe
A centralized event bus decouples subjects and observers further (e.g., in frameworks like React, Vue, or message queues).
MVC Architecture: Model (subject) notifies Views (observers) on data changes.
Reactive Programming: RxJava, React hooks (useEffect), or Vue’s reactivity system.
Stock Market Apps: Price updates broadcast to multiple charting components.
Social Media Feeds: New posts pushed to followers.
Pros & Cons
✅ Pros:
Loose coupling: Subjects don’t need to know observer details.
Dynamic relationships: Observers can be added/removed at runtime.
Reusability: Subjects and observers can be reused independently.
Scalability: Easy to add new observers without modifying the subject.
❌ Cons:
Memory leaks: Forgetting to detach observers can cause retention (common in Android/iOS UI).
Unexpected updates: Observers might be triggered in an unwanted order or cascade effects.
Performance: Many observers or frequent notifications can impact performance (consider async/queues).
Best Practices
Use weak references (or explicit detach()) to avoid memory leaks.
Prefer thread-safe implementations for multi-threaded environments (e.g., CopyOnWriteArrayList in Java).
Consider asynchronous notifications for heavy observer logic.
Document notification order if it matters (e.g., OrderedObserver).
Related Patterns
Mediator: Centralizes complex communications between objects (reduces direct observer dependencies).
Publish-Subscribe: Similar but uses a message broker/event bus for indirect communication.
MVC/MVVM: The Observer pattern is foundational in these architectures (Model → View updates).
Summary
The Observer pattern is essential for event-driven systems, enabling objects to react to changes in other objects without tight coupling. It’s widely used in UI frameworks, reactive programming, and distributed systems—but requires careful management of observer lifetimes to avoid leaks.