Observer Design Pattern
   HOME

TheInfoList



OR:

In
software design Software design is the process of conceptualizing how a software system will work before it is implemented or modified. Software design also refers to the direct result of the design process the concepts of how the software will work which co ...
and
software engineering Software engineering is a branch of both computer science and engineering focused on designing, developing, testing, and maintaining Application software, software applications. It involves applying engineering design process, engineering principl ...
, the observer pattern is a
software design pattern In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
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 Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
. 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 In computing, an event is a detectable occurrence or change in the system's state, such as user input, hardware interrupts, system notifications, or changes in data or conditions, that the system is designed to monitor. Events trigger responses or ...
systems in
event-driven programming In computer programming, event-driven programming is a programming paradigm in which the Control flow, flow of the program is determined by external Event (computing), events. User interface, UI events from computer mouse, mice, computer keyboard, ...
, 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 request HTTP (Hypertext Transfer Protocol) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, wher ...
s,
GPIO A general-purpose input/output (GPIO) is an uncommitted digital signal pin on an integrated circuit or electronic circuit (e.g. MCUs/ MPUs) board that can be used as an input or output, or both, and is controllable by software. GPIOs have no p ...
signals, updates from
distributed database A distributed database is a database in which data is stored across different physical locations. It may be stored in multiple computers located in the same physical location (e.g. a data centre); or maybe dispersed over a computer network, netwo ...
s, 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.


Relationship to publish–subscribe

The observer pattern and the
publish–subscribe pattern In software architecture, the publish–subscribe pattern (pub/sub) is a messaging pattern in which message senders, called publishers, categorize messages into classes (or ''topics''), and send them without needing to know which components ...
are closely related and often confused, as both support one-to-many communication between components. However, they differ significantly in architecture, degree of coupling, and common use cases. The table below summarizes the key differences: In practice, publish–subscribe systems evolved to address several limitations of the observer pattern. A typical observer implementation creates a tight coupling between the subject and its observers. This may limit scalability, flexibility, and maintainability, especially in distributed environments. Subjects and observers must conform to a shared interface, and both parties are aware of each other’s presence. To reduce this coupling, publish–subscribe systems introduce a message broker or event bus that intermediates between publishers and subscribers. This additional layer removes the need for direct references, allowing systems to evolve independently. Brokers may also support features like message persistence, delivery guarantees, topic-based filtering, and asynchronous communication. In some systems, the observer pattern is used internally to implement subscription mechanisms behind a publish–subscribe interface. In other cases, the patterns are applied independently. For example,
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
libraries and frameworks often offer both observer-like subscriptions (e.g., via callback registration) and decoupled pub-sub mechanisms (e.g., via event emitters or signals). Historically, in early graphical operating systems like
OS/2 OS/2 is a Proprietary software, proprietary computer operating system for x86 and PowerPC based personal computers. It was created and initially developed jointly by IBM and Microsoft, under the leadership of IBM software designer Ed Iacobucci, ...
and
Microsoft Windows Windows is a Product lining, product line of Proprietary software, proprietary graphical user interface, graphical operating systems developed and marketed by Microsoft. It is grouped into families and subfamilies that cater to particular sec ...
, the terms "publish–subscribe" and "event-driven programming" were often used as synonyms for the observer pattern. The observer pattern, as formalized in ''Design Patterns'', deliberately omits concerns such as unsubscription, notification filtering, delivery guarantees, and message logging. These advanced capabilities are typically implemented in robust message queuing systems, where the observer pattern may serve as a foundational mechanism but is not sufficient by itself. Related patterns include
mediator Mediation is a structured, voluntary process for resolving disputes, facilitated by a neutral third party known as the mediator. It is a structured, interactive process where an independent third party, the mediator, assists disputing parties ...
and singleton.


Limitations and solutions


Strong vs. weak references

A common drawback of the observer pattern is the potential for
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an objec ...
s, known as the lapsed listener problem. This occurs when a subject maintains strong references to its observers, preventing them from being garbage collected even if they are no longer needed elsewhere. Because the pattern typically requires both explicit registration and deregistration (as in the
dispose pattern In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close, dispose, free, release dep ...
), forgetting to unregister observers can leave dangling references. This issue can be mitigated by using
weak reference In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced ''only'' by weak references – meaning "every chain of re ...
s for observer references, allowing the garbage collector to reclaim observer objects that are no longer in use.


Throttling and temporal decoupling

In some applications, particularly user interfaces, the subject's state may change so frequently that notifying observers on every change is inefficient or counterproductive. For example, a view that re-renders on every minor change in a data model might become unresponsive or flicker. In such cases, the observer pattern can be modified to decouple notifications ''temporally'' by introducing a throttling mechanism, such as a timer. Rather than updating on every state change, the observer polls the subject or is notified at regular intervals, rendering an approximate but stable view of the model. This approach is commonly used for elements like progress bars, where the underlying process changes state rapidly. Instead of responding to every minor increment, the observer updates the visual display periodically, improving performance and usability. This form of temporal decoupling allows observers to remain responsive without being overwhelmed by high-frequency updates, while still reflecting the overall trend or progress of the subject’s state.


Structure


UML class and sequence diagram

In this UML
class diagram In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the re ...
, 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 In software engineering, a sequence diagram shows process interactions arranged in time sequence. This diagram depicts the processes and objects involved and the sequence of messages exchanged as needed to carry out the functionality. Sequence ...
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 Observer2objects, which request the changed data (getState()) from Subject1 to update (synchronize) their state.


UML class diagram


Example

While the library classe
java.util.Observer
an

exist, they have been
deprecated Deprecation is the discouragement of use of something human-made, such as a term, feature, design, or practice. Typically something is deprecated because it is claimed to be inferior compared to other options available. Something may be deprec ...
in Java 9 because the model implemented was quite limited. Below is an example written in
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
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

import java.util.ArrayList; import java.util.List; import java.util.Scanner; interface Observer class EventSource public class ObserverDemo


C#

C# provides the . and interfaces as well as documentation on how to implement the design pattern. class Payload class Subject : IObservable internal class Unsubscriber : IDisposable internal class Observer : IObserver


C++

This is a C++11 implementation. #include #include #include class Subject; //Forward declaration for usage in Observer class Observer ; // Subject is the base class for event generation class Subject ; Observer::Observer(Subject& subj) : subject(subj) Observer::~Observer() // Example of usage class ConcreteObserver: public Observer ; int main() The program output is like Got a notification Got a notification


Groovy

class EventSource println 'Enter Text: ' var eventSource = new EventSource() eventSource.addObserver eventSource.scanSystemIn()


Kotlin

import java.util.Scanner typealias Observer = (event: String) -> Unit; class EventSource fun main(arg: List)


Delphi

uses System.Generics.Collections, System.SysUtils; type IObserver = interface ' procedure Update(const AValue: string); end; type TObserverManager = class private FObservers: TList; public constructor Create; overload; destructor Destroy; override; procedure NotifyObservers(const AValue: string); procedure AddObserver(const AObserver: IObserver); procedure UnregisterObsrver(const AObserver: IObserver); end; type TListener = class(TInterfacedObject, IObserver) private FName: string; public constructor Create(const AName: string); reintroduce; procedure Update(const AValue: string); end; procedure TObserverManager.AddObserver(const AObserver: IObserver); begin if not FObservers.Contains(AObserver) then FObservers.Add(AObserver); end; begin FreeAndNil(FObservers); inherited; end; procedure TObserverManager.NotifyObservers(const AValue: string); var i: Integer; begin for i := 0 to FObservers.Count - 1 do FObservers Update(AValue); end; procedure TObserverManager.UnregisterObsrver(const AObserver: IObserver); begin if FObservers.Contains(AObserver) then FObservers.Remove(AObserver); end; constructor TListener.Create(const AName: string); begin inherited Create; FName := AName; end; procedure TListener.Update(const AValue: string); begin WriteLn(FName + ' listener received notification: ' + AValue); end; procedure TMyForm.ObserverExampleButtonClick(Sender: TObject); var LDoorNotify: TObserverManager; LListenerHusband: IObserver; LListenerWife: IObserver; begin LDoorNotify := TObserverManager.Create; try LListenerHusband := TListener.Create('Husband'); LDoorNotify.AddObserver(LListenerHusband); LListenerWife := TListener.Create('Wife'); LDoorNotify.AddObserver(LListenerWife); LDoorNotify.NotifyObservers('Someone is knocking on the door'); finally FreeAndNil(LDoorNotify); end; end; Output
Husband listener received notification: Someone is knocking on the door
Wife listener received notification: Someone is knocking on the door


Python

A similar example in
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
: class Observable: def __init__(self): self._observers = [] def register_observer(self, observer: Observer) -> None: self._observers.append(observer) def notify_observers(self, *args, **kwargs) -> None: for observer in self._observers: observer.notify(self, *args, **kwargs) class Observer: def __init__(self, observable: Observable): observable.register_observer(self) def notify(self, observable: Observable, *args, **kwargs) -> None: print("Got", args, kwargs, "From", observable) subject = Observable() observer = Observer(subject) subject.notify_observers("test", kw="python") # prints: Got ('test',) From <__main__.Observable object at 0x0000019757826FD0>


JavaScript

JavaScript has a deprecated function that was a more accurate implementation of the observer pattern. 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 = ; let Observer = Subject.add(Observer); Subject.setState(10); // Output in console.log - 10


See also

* Implicit invocation *
Client–server model The client–server model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients. Often clients and servers communicate ov ...
*The observer pattern is often used in the
entity–component–system Entity–component–system (ECS) is a Software architecture, software architectural pattern mostly used in video game development for the representation of game world objects. An ECS comprises ''entities'' composed from ''components'' of data, ...
pattern


References


External links

* {{Design Patterns Patterns Software design patterns Articles with example Java code Articles with example Python (programming language) code Articles with example C Sharp code