Observer pattern
≈ 8 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
In software design and software engineering, the observer pattern is a software design pattern in which an object, called the subject (also known as event source or event stream), maintains a list of its dependents, called observers (also known as event sinks), and automatically notifies them of any state changes, typically by calling one of their methods. The subject knows its observers through a standardized interface and manages the subscription list directly. This pattern creates a one-to-many dependency where multiple observers can listen to a single subject, but the coupling is typically synchronous and direct—the subject calls observer methods when changes occur, though asynchronous implementations using event queues are possible. Unlike the publish-subscribe pattern, there is no intermediary broker; the subject and observers have direct references to each other. It is commonly used to implement event handling systems in event-driven programming, particularly in-process systems like GUI toolkits or MVC frameworks. This makes the pattern well-suited to processing data that arrives unpredictably—such as user input, HTTP requests, GPIO signals, updates from distributed databases, or changes in a GUI model.
In software design and software engineering, the observer pattern is a software design pattern in which an object, called the subject (also known as event source or event stream), maintains a list of its dependents, called observers (also known as event sinks), and automatically notifies them of any state changes, typically by calling one of their methods. The subject knows its observers through a standardized interface and manages the subscription list directly. This pattern creates a one-to-many dependency where multiple observers can listen to a single subject, but the coupling is typically synchronous and direct—the subject calls observer methods when changes occur, though asynchronous implementations using event queues are possible. Unlike the publish-subscribe pattern, there is no intermediary broker; the subject and observers have direct references to each other. It is commonly used to implement event handling systems in event-driven programming, particularly in-process systems like GUI toolkits or MVC frameworks. This makes the pattern well-suited to processing data that arrives unpredictably—such as user input, HTTP requests, GPIO signals, updates from distributed databases, or changes in a GUI model.
Overview
The observer design pattern is a behavioural pattern listed among the 23 well-known "Gang of Four" design patterns that address recurring design challenges in order to design flexible and reusable object-oriented software, yielding objects that are easier to implement, change, test, and reuse. The observer pattern addresses the following requirements: A one-to-many dependency between objects should be defined without making the objects tightly coupled. When one object changes state, an open-ended number of dependent objects should be updated automatically. An object can notify multiple other objects. The naive approach would be for one object (subject) to directly call specific methods on each dependent object. This creates tight coupling because the subject must know the concrete types and specific interfaces of all dependent objects, making the code inflexible and hard to extend. However, this direct approach may be preferable in performance-critical scenarios (such as low-level kernel structures or real-time systems) where the overhead of abstraction is unacceptable and compile-time optimization is crucial. The observer pattern provides a more flexible alternative by establishing a standard notification protocol: Define Subject and Observer objects with standardized interfaces. When a subject changes state, all registered observers are notified and updated automatically. The subject manages its own state while also maintaining a list of observers and notifying them of state changes by calling their update() operation. The responsibility of observers is to register and unregister themselves with a subject (in order to be notified of state changes) and to update their state (to synchronize it with the subject's state) when they are notified. This approach makes subject and observers loosely coupled through interface standardization. The subject only needs to know that observers implement the update() method—it has no knowledge of observers' concrete types or internal implementation details. Observers can be added and removed independently at run time.
Structure
UML class and sequence diagram
In this UML class diagram, the Subject class does not update the state of dependent objects directly. Instead, Subject refers to the Observer interface ( update() ) for updating state, which makes the Subject independent of how the state of dependent objects is updated. The Observer1 and Observer2 classes implement the Observer interface by synchronizing their state with subject's state. The UML sequence diagram shows the runtime interactions: The Observer1 and Observer2 objects call attach(this) on Subject1 to register themselves. Assuming that the state of Subject1 changes, Subject1 calls notify() on itself. notify() calls update() on the registered Observer1 and Observer2 objects, which request the changed data ( getState() ) from Subject1 to update (synchronize) their state.
UML class diagram
class diagram of Observer pattern
Example
While the library classes java.util.Observer and java.util.Observable exist, they have been deprecated in Java 9 because the model implemented was quite limited. Below is an example written in Java that takes keyboard input and handles each input line as an event. When a string is supplied from System.in , the method notifyObservers() is then called in order to notify all observers of the event's occurrence, in the form of an invocation of their update methods.
Java
package org.wikipedia.examples; import java.util.ArrayList; import java.util.List; import java.util.Scanner; interface Observer { void update(String event); } class EventSource { List observers = new ArrayList<>(); public void notifyObservers(String event) { observers.forEach(observer -> observer.update(event)); } public void addObserver(Observer observer) { observers.add(observer); } public void scanSystemIn() { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); notifyObservers(line); } } } public class ObserverDemo { public static void main(String[] args) { System.out.println("Enter Text: "); EventSource eventSource = new EventSource(); eventSource.addObserver(event -> System.out.printf("Received response: %s%n", event)); eventSource.scanSystemIn(); } }
C#
C# provides the . and interfaces as well as documentation on how to implement the design pattern. namespace Wikipedia.Examples; using System; using System.Collections.Generic; class Payload { internal string Message { get; init; } } class Subject : IObservable { private readonly List > _observers = new(); IDisposable IObservable .Subscribe(IObserver observer) { if (!_observers.Contains(observer)) { _observers.Add(observer); } return new Unsubscriber(observer, _observers); } internal void SendMessage(string message) { foreach (IObserver observer in _observers) { observer.OnNext(new Payload { Message = message }); } } } internal class Unsubscriber : IDisposable { private readonly IObserver _observer; private readonly ICollection > _observers; internal Unsubscriber( IObserver observer, ICollection > observers) { _observer = observer; _observers = observers; } void IDisposable.Dispose() { if (_observer != null && _observers.Contains(_observer)) { _observers.Remove(_observer); } } } internal class Observer : IObserver { private string _message; public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(Payload value) { _message = value.Message; } internal IDisposable Register(IObservable subject) { return subject.Subscribe(this); } }
C++
This is a C++23 implementation. import std; using std::reference_wrapper; using std::vector; class Subject; // Forward declaration for usage in Observer class Observer { private: // Reference to a Subject object to detach in the destructor Subject& subject; public: explicit Observer(Subject& subj): subject{subj} { subject.attach(*this); } virtual ~Observer() { subject.detach(*this); } Observer(const Observer&) = delete; Observer& operator=(const Observer&) = delete; virtual void update(Subject& s) const = 0; }; // Subject is the base class for event generation class Subject { private: vector This would fire events upon change to the observed object. Without the deprecated function, the pattern may be implemented with more explicit code: let Subject = { _state: 0, _observers: [], add: function(observer) { this._observers.push(observer); }, getState: function() { return this._state; }, setState: function(value) { this._state = value; for (let i = 0; i
See also
Implicit invocation Client–server model The observer pattern is often used in the entity–component–system pattern
References
External links
Text derived from https://en.wikipedia.org/w/index.php?oldid=1339059800 under CC BY-SA 4.0; modifications have been made.