<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.sarg.dev/index.php?action=history&amp;feed=atom&amp;title=Observer_pattern</id>
	<title>Observer pattern - Revision history</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.sarg.dev/index.php?action=history&amp;feed=atom&amp;title=Observer_pattern"/>
	<link rel="alternate" type="text/html" href="https://wiki.sarg.dev/index.php?title=Observer_pattern&amp;action=history"/>
	<updated>2026-06-22T14:17:05Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.44.2</generator>
	<entry>
		<id>https://wiki.sarg.dev/index.php?title=Observer_pattern&amp;diff=118965&amp;oldid=prev</id>
		<title>~2025-30963-97: This is not vandalism. This edit adds namespace names to the code samples and simplifies a declaration by using an implicit constructor call. Nothing about this edit is vandalism, and me continuing to revert it is not edit warring either. What you are doing is disruptive and refusing to read edit content.</title>
		<link rel="alternate" type="text/html" href="https://wiki.sarg.dev/index.php?title=Observer_pattern&amp;diff=118965&amp;oldid=prev"/>
		<updated>2025-11-04T20:21:29Z</updated>

		<summary type="html">&lt;p&gt;This is not vandalism. This edit adds namespace names to the code samples and simplifies a declaration by using an implicit constructor call. Nothing about this edit is vandalism, and me continuing to revert it is not edit warring either. What you are doing is disruptive and refusing to read edit content.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{Short description|Software design pattern based on an event-updated object with a list of dependents}}&lt;br /&gt;
&lt;br /&gt;
In [[software design]] and [[software engineering]], the &amp;#039;&amp;#039;&amp;#039;observer pattern&amp;#039;&amp;#039;&amp;#039; is a [[software design pattern]] in which an object, called the &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;subject&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; (also known as &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;event source&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; or &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;event stream&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;), maintains a list of its dependents, called &amp;#039;&amp;#039;&amp;#039;observers&amp;#039;&amp;#039;&amp;#039; (also known as &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;event sinks&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;), and automatically notifies them of any [[state (computer science)|state changes]], typically by calling one of their [[method (computer science)|methods]]. The subject knows its observers through a standardized interface and manages the subscription list directly.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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 request]]s, [[general-purpose input/output|GPIO]] signals, updates from [[distributed database]]s, or changes in a [[graphical user interface|GUI]] model.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
The observer design pattern is a behavioural pattern listed among the 23 well-known [[Design Patterns|&amp;quot;Gang of Four&amp;quot; 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.&amp;lt;ref name=&amp;quot;GoF&amp;quot;&amp;gt;{{cite book|author=Erich Gamma|url=https://archive.org/details/designpatternsel00gamm/page/293|title=Design Patterns: Elements of Reusable Object-Oriented Software|last2=Richard Helm|last3=Ralph Johnson|last4=John Vlissides|publisher=Addison Wesley|year=1994|isbn=0-201-63361-2|pages=[https://archive.org/details/designpatternsel00gamm/page/293 293ff]|url-access=registration}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The observer pattern addresses the following requirements:&amp;lt;ref&amp;gt;{{cite web |title=Observer Design Pattern |url=https://www.geeksforgeeks.org/observer-pattern-set-1-introduction/ |access-date= |website=www.geeksforgeeks.org}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* A one-to-many dependency between objects should be defined without making the objects tightly coupled.&lt;br /&gt;
* When one object changes state, an open-ended number of dependent objects should be updated automatically.&lt;br /&gt;
* An object can notify multiple other objects.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
The observer pattern provides a more flexible alternative by establishing a standard notification protocol:&lt;br /&gt;
&lt;br /&gt;
# Define &amp;lt;code&amp;gt;Subject&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Observer&amp;lt;/code&amp;gt; objects with standardized interfaces.&lt;br /&gt;
# When a subject changes state, all registered observers are notified and updated automatically.&lt;br /&gt;
# The subject manages its own state while also maintaining a list of observers and notifying them of state changes by calling their &amp;lt;code&amp;gt;update()&amp;lt;/code&amp;gt; operation.&lt;br /&gt;
# 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&amp;#039;s state) when they are notified.&lt;br /&gt;
&lt;br /&gt;
This approach makes subject and observers loosely coupled through interface standardization. The subject only needs to know that observers implement the &amp;lt;code&amp;gt;update()&amp;lt;/code&amp;gt; method—it has no knowledge of observers&amp;#039; concrete types or internal implementation details. Observers can be added and removed independently at run time.&lt;br /&gt;
&lt;br /&gt;
== Relationship to publish–subscribe ==&lt;br /&gt;
The observer pattern and the [[publish–subscribe pattern]] 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.&lt;br /&gt;
&lt;br /&gt;
The table below summarizes the key differences:&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
!Feature&lt;br /&gt;
!&amp;#039;&amp;#039;&amp;#039;Observer Pattern&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
!&amp;#039;&amp;#039;&amp;#039;Publish–Subscribe Pattern&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Coupling&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|&amp;#039;&amp;#039;Tightly coupled&amp;#039;&amp;#039; — the subject holds direct references to its observers via a standardized interface.&lt;br /&gt;
|&amp;#039;&amp;#039;Loosely coupled&amp;#039;&amp;#039; — publishers and subscribers are unaware of each other.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Communication&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|&amp;#039;&amp;#039;Direct&amp;#039;&amp;#039; — the subject calls observer methods, typically synchronously.&lt;br /&gt;
|&amp;#039;&amp;#039;Indirect&amp;#039;&amp;#039; — a broker (message bus or event manager) dispatches messages to subscribers.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Knowledge of Participants&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|The subject knows its observers.&lt;br /&gt;
|Publisher and subscriber are decoupled; neither knows about the other.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Scalability&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|Suitable for in-process systems like GUI toolkits.&lt;br /&gt;
|More scalable; supports distributed systems and asynchronous messaging.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Synchronous or Asynchronous&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|Typically synchronous but can be asynchronous with event queues.&lt;br /&gt;
|Typically asynchronous but can be synchronous.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Filtering&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|Limited — observers receive all events and filter internally.&lt;br /&gt;
|Rich filtering — brokers may filter by topic, content, or rules.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Fault Tolerance&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|Observer failures can affect the subject.&lt;br /&gt;
|Failures are isolated; the broker decouples participants.&lt;br /&gt;
|-&lt;br /&gt;
|&amp;#039;&amp;#039;&amp;#039;Typical Usage&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
|GUI frameworks, MVC architecture, local object notifications.&lt;br /&gt;
|Microservices, distributed systems, messaging middleware.&lt;br /&gt;
|}&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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]] 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).&amp;lt;ref&amp;gt;[https://github.com/millermedeiros/js-signals/wiki/Comparison-between-different-Observer-Pattern-implementations Comparison between different observer pattern implementations] — Moshe Bindler, 2015 (GitHub)&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;[https://www.safaribooksonline.com/library/view/learning-javascript-design/9781449334840/ch09s05.html Differences between pub/sub and observer pattern] — &amp;#039;&amp;#039;The Observer Pattern&amp;#039;&amp;#039; by Adi Osmani (Safari Books Online)&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Historically, in early graphical operating systems like [[OS/2]] and [[Microsoft Windows]], the terms &amp;quot;publish–subscribe&amp;quot; and &amp;quot;event-driven programming&amp;quot; were often used as synonyms for the observer pattern.&amp;lt;ref&amp;gt;[https://books.google.com/books?id=18wFKrkDdM0C&amp;amp;pg=PA230 The Windows Programming Experience], [[Charles Petzold]], November 10, 1992, &amp;#039;&amp;#039;PC Magazine&amp;#039;&amp;#039; ([[Google Books]])&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The observer pattern, as formalized in &amp;#039;&amp;#039;Design Patterns&amp;#039;&amp;#039;,&amp;lt;ref name=&amp;quot;GoF&amp;quot; /&amp;gt; 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.&lt;br /&gt;
&lt;br /&gt;
Related patterns include [[Mediator pattern|mediator]] and [[Singleton pattern|singleton]].&lt;br /&gt;
&lt;br /&gt;
== Limitations and solutions ==&lt;br /&gt;
&lt;br /&gt;
=== Strong vs. weak references ===&lt;br /&gt;
A common drawback of the observer pattern is the potential for [[memory leak]]s, known as the [[lapsed listener problem]]. This occurs when a subject maintains strong references to its observers, preventing them from being [[Garbage collection (computer science)|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]]), forgetting to unregister observers can leave dangling references. This issue can be mitigated by using [[weak reference]]s for observer references, allowing the garbage collector to reclaim observer objects that are no longer in use.&lt;br /&gt;
&lt;br /&gt;
=== Throttling and temporal decoupling ===&lt;br /&gt;
In some applications, particularly user interfaces, the subject&amp;#039;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.&lt;br /&gt;
&lt;br /&gt;
In such cases, the observer pattern can be modified to decouple notifications &amp;#039;&amp;#039;temporally&amp;#039;&amp;#039; 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.&lt;br /&gt;
&lt;br /&gt;
This approach is commonly used for elements like [[Progress bar|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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Structure==&lt;br /&gt;
===UML class and sequence diagram===&lt;br /&gt;
&lt;br /&gt;
[[File:w3sDesign Observer Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the observer design pattern. &amp;lt;ref&amp;gt;{{cite web|title=The Observer design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=b07&amp;amp;ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}&amp;lt;/ref&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
In this [[Unified Modeling Language|UML]] [[class diagram]], the &amp;lt;code&amp;gt;Subject&amp;lt;/code&amp;gt; class does not update the state of dependent objects directly. Instead, &amp;lt;code&amp;gt;Subject&amp;lt;/code&amp;gt; refers to the &amp;lt;code&amp;gt;Observer&amp;lt;/code&amp;gt; interface (&amp;lt;code&amp;gt;update()&amp;lt;/code&amp;gt;) for updating state, which makes the &amp;lt;code&amp;gt;Subject&amp;lt;/code&amp;gt; independent of how the state of dependent objects is updated. The &amp;lt;code&amp;gt;Observer1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Observer2&amp;lt;/code&amp;gt; classes implement the &amp;lt;code&amp;gt;Observer&amp;lt;/code&amp;gt; interface by synchronizing their state with subject&amp;#039;s state.&lt;br /&gt;
&lt;br /&gt;
The [[Unified Modeling Language|UML]] [[sequence diagram]] shows the runtime interactions: The &amp;lt;code&amp;gt;Observer1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Observer2&amp;lt;/code&amp;gt; objects call &amp;lt;code&amp;gt;attach(this)&amp;lt;/code&amp;gt; on &amp;lt;code&amp;gt;Subject1&amp;lt;/code&amp;gt; to register themselves. Assuming that the state of &amp;lt;code&amp;gt;Subject1&amp;lt;/code&amp;gt; changes, &amp;lt;code&amp;gt;Subject1&amp;lt;/code&amp;gt; calls &amp;lt;code&amp;gt;notify()&amp;lt;/code&amp;gt; on itself. &amp;lt;code&amp;gt;notify()&amp;lt;/code&amp;gt; calls &amp;lt;code&amp;gt;update()&amp;lt;/code&amp;gt; on the registered &amp;lt;code&amp;gt;Observer1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Observer2&amp;lt;/code&amp;gt;objects, which request the changed data (&amp;lt;code&amp;gt;getState()&amp;lt;/code&amp;gt;) from &amp;lt;code&amp;gt;Subject1&amp;lt;/code&amp;gt; to update (synchronize) their state.&lt;br /&gt;
&lt;br /&gt;
===UML class diagram===&lt;br /&gt;
[[File:Observer w update.svg|none|thumb|500x500px|[[Unified Modeling Language|UML]] class diagram of Observer pattern]]&lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
&amp;lt;!-- Wikipedia is not a list of examples. Do not add examples from your favorite programming language here; this page exists to explain the design pattern, not to show how it interacts with subtleties of every language under the sun. Feel free to add examples here: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Observer  --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While the library classes [https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Observer.html &amp;lt;code&amp;gt;java.util.Observer&amp;lt;/code&amp;gt;] and [https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Observable.html &amp;lt;code&amp;gt;java.util.Observable&amp;lt;/code&amp;gt;] exist, they have been [[Deprecation|deprecated]] in Java 9 because the model implemented was quite limited.&lt;br /&gt;
&lt;br /&gt;
Below is an example written in [[Java (programming language)|Java]] that takes keyboard input and handles each input line as an event. When a string is supplied from &amp;lt;code&amp;gt;System.in&amp;lt;/code&amp;gt;, the method &amp;lt;code&amp;gt;notifyObservers()&amp;lt;/code&amp;gt; is then called in order to notify all observers of the event&amp;#039;s occurrence, in the form of an invocation of their update methods.&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
package org.wikipedia.examples;&lt;br /&gt;
&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
import java.util.Scanner;&lt;br /&gt;
&lt;br /&gt;
interface Observer {&lt;br /&gt;
    void update(String event);&lt;br /&gt;
}&lt;br /&gt;
  &lt;br /&gt;
class EventSource {&lt;br /&gt;
    List&amp;lt;Observer&amp;gt; observers = new ArrayList&amp;lt;&amp;gt;();&lt;br /&gt;
  &lt;br /&gt;
    public void notifyObservers(String event) {&lt;br /&gt;
        observers.forEach(observer -&amp;gt; observer.update(event));&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    public void addObserver(Observer observer) {&lt;br /&gt;
        observers.add(observer);&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    public void scanSystemIn() {&lt;br /&gt;
        Scanner scanner = new Scanner(System.in);&lt;br /&gt;
        while (scanner.hasNextLine()) {&lt;br /&gt;
            String line = scanner.nextLine();&lt;br /&gt;
            notifyObservers(line);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class ObserverDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        System.out.println(&amp;quot;Enter Text: &amp;quot;);&lt;br /&gt;
        EventSource eventSource = new EventSource();&lt;br /&gt;
        &lt;br /&gt;
        eventSource.addObserver(event -&amp;gt; System.out.printf(&amp;quot;Received response: %s%n&amp;quot;, event));&lt;br /&gt;
&lt;br /&gt;
        eventSource.scanSystemIn();&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
C# provides the {{Code|IObservable}}.&amp;lt;ref&amp;gt;{{cite web |title=IObservable Interface (System) |url=https://learn.microsoft.com/en-us/dotnet/api/system.iobservable-1?view=net-8.0 |website=learn.microsoft.com |access-date=9 November 2024 |language=en-us}}&amp;lt;/ref&amp;gt; and {{Code|IObserver}}&amp;lt;ref&amp;gt;{{cite web |title=IObserver Interface (System) |url=https://learn.microsoft.com/en-us/dotnet/api/system.iobserver-1?view=net-8.0 |website=learn.microsoft.com |access-date=9 November 2024 |language=en-us}}&amp;lt;/ref&amp;gt; interfaces as well as documentation on how to implement the design pattern.&amp;lt;ref&amp;gt;{{cite web |title=Observer design pattern - .NET |url=https://learn.microsoft.com/en-us/dotnet/standard/events/observer-design-pattern |website=learn.microsoft.com |access-date=9 November 2024 |language=en-us |date=25 May 2023}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
namespace Wikipedia.Examples;&lt;br /&gt;
&lt;br /&gt;
using System;&lt;br /&gt;
using System.Collections.Generic;&lt;br /&gt;
&lt;br /&gt;
class Payload&lt;br /&gt;
{&lt;br /&gt;
    internal string Message { get; init; }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class Subject : IObservable&amp;lt;Payload&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    private readonly List&amp;lt;IObserver&amp;lt;Payload&amp;gt;&amp;gt; _observers = new();&lt;br /&gt;
&lt;br /&gt;
    IDisposable IObservable&amp;lt;Payload&amp;gt;.Subscribe(IObserver&amp;lt;Payload&amp;gt; observer)&lt;br /&gt;
    {         &lt;br /&gt;
        if (!_observers.Contains(observer))&lt;br /&gt;
        {&lt;br /&gt;
            _observers.Add(observer);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        return new Unsubscriber(observer, _observers);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    internal void SendMessage(string message)&lt;br /&gt;
    {&lt;br /&gt;
        foreach (IObserver&amp;lt;Payload&amp;gt; observer in _observers)&lt;br /&gt;
        {&lt;br /&gt;
            observer.OnNext(new Payload { Message = message });&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
internal class Unsubscriber : IDisposable&lt;br /&gt;
{&lt;br /&gt;
    private readonly IObserver&amp;lt;Payload&amp;gt; _observer;&lt;br /&gt;
    private readonly ICollection&amp;lt;IObserver&amp;lt;Payload&amp;gt;&amp;gt; _observers;&lt;br /&gt;
&lt;br /&gt;
    internal Unsubscriber(&lt;br /&gt;
        IObserver&amp;lt;Payload&amp;gt; observer,&lt;br /&gt;
        ICollection&amp;lt;IObserver&amp;lt;Payload&amp;gt;&amp;gt; observers)&lt;br /&gt;
    {&lt;br /&gt;
        _observer = observer;&lt;br /&gt;
        _observers = observers;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    void IDisposable.Dispose()&lt;br /&gt;
    {&lt;br /&gt;
        if (_observer != null &amp;amp;&amp;amp; _observers.Contains(_observer))&lt;br /&gt;
        {&lt;br /&gt;
            _observers.Remove(_observer);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
internal class Observer : IObserver&amp;lt;Payload&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    private string _message;&lt;br /&gt;
&lt;br /&gt;
    public void OnCompleted()&lt;br /&gt;
    {&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void OnError(Exception error)&lt;br /&gt;
    {&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void OnNext(Payload value)&lt;br /&gt;
    {&lt;br /&gt;
        _message = value.Message;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    internal IDisposable Register(IObservable&amp;lt;Payload&amp;gt; subject)&lt;br /&gt;
    {&lt;br /&gt;
        return subject.Subscribe(this);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===C++===&lt;br /&gt;
This is a C++23 implementation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c++&amp;quot;&amp;gt;&lt;br /&gt;
import std;&lt;br /&gt;
&lt;br /&gt;
using std::reference_wrapper;&lt;br /&gt;
using std::vector;&lt;br /&gt;
&lt;br /&gt;
class Subject; // Forward declaration for usage in Observer&lt;br /&gt;
&lt;br /&gt;
class Observer {&lt;br /&gt;
private:&lt;br /&gt;
    // Reference to a Subject object to detach in the destructor&lt;br /&gt;
    Subject&amp;amp; subject;&lt;br /&gt;
public:&lt;br /&gt;
    explicit Observer(Subject&amp;amp; subj):     &lt;br /&gt;
        subject{subj} {&lt;br /&gt;
        subject.attach(*this);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    virtual ~Observer() {&lt;br /&gt;
        subject.detach(*this);&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    Observer(const Observer&amp;amp;) = delete;&lt;br /&gt;
    Observer&amp;amp; operator=(const Observer&amp;amp;) = delete;&lt;br /&gt;
&lt;br /&gt;
    virtual void update(Subject&amp;amp; s) const = 0;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Subject is the base class for event generation&lt;br /&gt;
class Subject {&lt;br /&gt;
private:&lt;br /&gt;
    vector&amp;lt;RefObserver&amp;gt; observers;&lt;br /&gt;
public:&lt;br /&gt;
    using RefObserver = reference_wrapper&amp;lt;const Observer&amp;gt;;&lt;br /&gt;
  &lt;br /&gt;
    // Notify all the attached observers&lt;br /&gt;
    void notify() {&lt;br /&gt;
        for (const Observer&amp;amp; x: observers) {&lt;br /&gt;
            x.get().update(*this);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    // Add an observer&lt;br /&gt;
    void attach(const Observer&amp;amp; observer) {&lt;br /&gt;
        observers.push_back(observer);&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    // Remove an observer&lt;br /&gt;
    void detach(Observer&amp;amp; observer) {&lt;br /&gt;
        observers.remove_if([&amp;amp;observer](const RefObserver&amp;amp; obj) -&amp;gt; bool { &lt;br /&gt;
            return &amp;amp;obj.get() == &amp;amp;observer; &lt;br /&gt;
        });&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
// Example of usage&lt;br /&gt;
class ConcreteObserver: public Observer {&lt;br /&gt;
public:&lt;br /&gt;
    explicit ConcreteObserver(Subject&amp;amp; subj): &lt;br /&gt;
        Observer(subj) {}&lt;br /&gt;
  &lt;br /&gt;
    // Get notification&lt;br /&gt;
    void update(Subject&amp;amp;) const override {&lt;br /&gt;
        std::println(&amp;quot;Got a notification&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char* argv[]) {&lt;br /&gt;
    Subject cs;&lt;br /&gt;
    ConcreteObserver co1(cs);&lt;br /&gt;
    ConcreteObserver co2(cs);&lt;br /&gt;
    cs.notify();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
The program output is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c++&amp;quot;&amp;gt;&lt;br /&gt;
Got a notification&lt;br /&gt;
Got a notification&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Groovy===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;groovy&amp;quot;&amp;gt;&lt;br /&gt;
class EventSource {&lt;br /&gt;
    private observers = []&lt;br /&gt;
&lt;br /&gt;
    private notifyObservers(String event) {&lt;br /&gt;
        observers.each { it(event) }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    void addObserver(observer) {&lt;br /&gt;
        observers += observer&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    void scanSystemIn() {&lt;br /&gt;
        var scanner = new Scanner(System.in)&lt;br /&gt;
        while (scanner) {&lt;br /&gt;
            var line = scanner.nextLine()&lt;br /&gt;
            notifyObservers(line)&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
println &amp;#039;Enter Text: &amp;#039;&lt;br /&gt;
var eventSource = new EventSource()&lt;br /&gt;
&lt;br /&gt;
eventSource.addObserver { event -&amp;gt;&lt;br /&gt;
    println &amp;quot;Received response: $event&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
eventSource.scanSystemIn()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Kotlin===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;kotlin&amp;quot;&amp;gt;&lt;br /&gt;
import java.util.Scanner&lt;br /&gt;
&lt;br /&gt;
typealias Observer = (event: String) -&amp;gt; Unit;&lt;br /&gt;
&lt;br /&gt;
class EventSource {&lt;br /&gt;
    private var observers = mutableListOf&amp;lt;Observer&amp;gt;()&lt;br /&gt;
&lt;br /&gt;
    private fun notifyObservers(event: String) {&lt;br /&gt;
        observers.forEach { it(event) }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    fun addObserver(observer: Observer) {&lt;br /&gt;
        observers += observer&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    fun scanSystemIn() {&lt;br /&gt;
        val scanner = Scanner(System.`in`)&lt;br /&gt;
        while (scanner.hasNext()) {&lt;br /&gt;
            val line = scanner.nextLine()&lt;br /&gt;
            notifyObservers(line)&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;kotlin&amp;quot;&amp;gt;&lt;br /&gt;
fun main(arg: List&amp;lt;String&amp;gt;) {&lt;br /&gt;
    println(&amp;quot;Enter Text: &amp;quot;)&lt;br /&gt;
    val eventSource = EventSource()&lt;br /&gt;
&lt;br /&gt;
    eventSource.addObserver { event -&amp;gt;&lt;br /&gt;
        println(&amp;quot;Received response: $event&amp;quot;)&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    eventSource.scanSystemIn()&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Delphi===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;delphi&amp;quot;&amp;gt;&lt;br /&gt;
uses&lt;br /&gt;
  System.Generics.Collections, System.SysUtils;&lt;br /&gt;
&lt;br /&gt;
type&lt;br /&gt;
  IObserver = interface&lt;br /&gt;
    [&amp;#039;{0C8F4C5D-1898-4F24-91DA-63F1DD66A692}&amp;#039;]&lt;br /&gt;
    procedure Update(const AValue: string);&lt;br /&gt;
  end;&lt;br /&gt;
&lt;br /&gt;
type&lt;br /&gt;
  TObserverManager = class&lt;br /&gt;
  private&lt;br /&gt;
    FObservers: TList&amp;lt;IObserver&amp;gt;;&lt;br /&gt;
  public&lt;br /&gt;
    constructor Create; overload;&lt;br /&gt;
    destructor Destroy; override;&lt;br /&gt;
    procedure NotifyObservers(const AValue: string);&lt;br /&gt;
    procedure AddObserver(const AObserver: IObserver);&lt;br /&gt;
    procedure UnregisterObserver(const AObserver: IObserver);&lt;br /&gt;
  end;&lt;br /&gt;
&lt;br /&gt;
type&lt;br /&gt;
  TListener = class(TInterfacedObject, IObserver)&lt;br /&gt;
  private&lt;br /&gt;
    FName: string;&lt;br /&gt;
  public&lt;br /&gt;
    constructor Create(const AName: string); reintroduce;&lt;br /&gt;
    procedure Update(const AValue: string);&lt;br /&gt;
  end;&lt;br /&gt;
&lt;br /&gt;
procedure TObserverManager.AddObserver(const AObserver: IObserver);&lt;br /&gt;
begin&lt;br /&gt;
  if not FObservers.Contains(AObserver)&lt;br /&gt;
    then FObservers.Add(AObserver);&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
begin&lt;br /&gt;
  FreeAndNil(FObservers);&lt;br /&gt;
  inherited;&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
procedure TObserverManager.NotifyObservers(const AValue: string);&lt;br /&gt;
var&lt;br /&gt;
  i: Integer;&lt;br /&gt;
begin&lt;br /&gt;
  for i := 0 to FObservers.Count - 1 do&lt;br /&gt;
    FObservers[i].Update(AValue);&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
procedure TObserverManager.UnregisterObserver(const AObserver: IObserver);&lt;br /&gt;
begin&lt;br /&gt;
  if FObservers.Contains(AObserver)&lt;br /&gt;
    then FObservers.Remove(AObserver);&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
constructor TListener.Create(const AName: string);&lt;br /&gt;
begin&lt;br /&gt;
  inherited Create;&lt;br /&gt;
  FName := AName;&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
procedure TListener.Update(const AValue: string);&lt;br /&gt;
begin&lt;br /&gt;
  WriteLn(FName + &amp;#039; listener received notification: &amp;#039; + AValue);&lt;br /&gt;
end;&lt;br /&gt;
&lt;br /&gt;
procedure TMyForm.ObserverExampleButtonClick(Sender: TObject);&lt;br /&gt;
var&lt;br /&gt;
  LDoorNotify: TObserverManager;&lt;br /&gt;
  LListenerHusband: IObserver;&lt;br /&gt;
  LListenerWife: IObserver;&lt;br /&gt;
begin&lt;br /&gt;
  LDoorNotify := TObserverManager.Create;&lt;br /&gt;
  try&lt;br /&gt;
    LListenerHusband := TListener.Create(&amp;#039;Husband&amp;#039;);&lt;br /&gt;
    LDoorNotify.AddObserver(LListenerHusband);&lt;br /&gt;
    LListenerWife := TListener.Create(&amp;#039;Wife&amp;#039;);&lt;br /&gt;
    LDoorNotify.AddObserver(LListenerWife);&lt;br /&gt;
    LDoorNotify.NotifyObservers(&amp;#039;Someone is knocking on the door&amp;#039;);&lt;br /&gt;
  finally&lt;br /&gt;
    FreeAndNil(LDoorNotify);&lt;br /&gt;
  end;&lt;br /&gt;
end;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Output&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Husband listener received notification: Someone is knocking on the door&lt;br /&gt;
Wife listener received notification: Someone is knocking on the door&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Python===&lt;br /&gt;
A similar example in [[Python_(programming_language)|Python]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from typing import Any&lt;br /&gt;
&lt;br /&gt;
class Subject:&lt;br /&gt;
    _observers: list[Observer]&lt;br /&gt;
&lt;br /&gt;
    def __init__(self) -&amp;gt; None:&lt;br /&gt;
        self._observers = []&lt;br /&gt;
&lt;br /&gt;
    def register_observer(self, observer: Observer) -&amp;gt; None:&lt;br /&gt;
        self._observers.append(observer)&lt;br /&gt;
&lt;br /&gt;
    def notify_observers(self, *args: tuple[Any, ...], **kwargs: dict[str, Any]) -&amp;gt; None:&lt;br /&gt;
        for observer in self._observers:&lt;br /&gt;
            observer.notify(self, *args, **kwargs)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
class Observer:&lt;br /&gt;
    def __init__(self, subject: Subject) -&amp;gt; None:&lt;br /&gt;
        subject.register_observer(self)&lt;br /&gt;
&lt;br /&gt;
    def notify(self, subject: Subject, *args: tuple[Any, ...], **kwargs: dict[str, Any]) -&amp;gt; None:&lt;br /&gt;
        print(f&amp;quot;Got {args}, {kwargs} from {subject}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
subject: Subject = Subject()&lt;br /&gt;
observer: Observer = Observer(subject)&lt;br /&gt;
subject.notify_observers(&amp;quot;test&amp;quot;, kw=&amp;quot;python&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# prints: Got (&amp;#039;test&amp;#039;,) {&amp;#039;kw&amp;#039;: &amp;#039;python&amp;#039;} From &amp;lt;__main__.Observable object at 0x0000019757826FD0&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===JavaScript===&lt;br /&gt;
&lt;br /&gt;
JavaScript has a deprecated {{code|Object.observe}} function that was a more accurate implementation of the observer pattern.&amp;lt;ref&amp;gt;{{Cite web|url=https://stackoverflow.com/a/50862441/887092|title = jQuery - Listening for variable changes in JavaScript}}&amp;lt;/ref&amp;gt; This would fire events upon change to the observed object. Without the deprecated {{code|Object.observe}} function, the pattern may be implemented with more explicit code:&amp;lt;ref&amp;gt;{{Cite web|url=https://stackoverflow.com/a/37403125/887092|title = Jquery - Listening for variable changes in JavaScript}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
let Subject = {&lt;br /&gt;
    _state: 0,&lt;br /&gt;
    _observers: [],&lt;br /&gt;
    add: function(observer) {&lt;br /&gt;
        this._observers.push(observer);&lt;br /&gt;
    },&lt;br /&gt;
    getState: function() {&lt;br /&gt;
        return this._state;&lt;br /&gt;
    },&lt;br /&gt;
    setState: function(value) {&lt;br /&gt;
        this._state = value;&lt;br /&gt;
        for (let i = 0; i &amp;lt; this._observers.length; i++)&lt;br /&gt;
        {&lt;br /&gt;
            this._observers[i].signal(this);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
let Observer = {&lt;br /&gt;
    signal: function(subject) {&lt;br /&gt;
        let currentValue = subject.getState();&lt;br /&gt;
        console.log(currentValue);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Subject.add(Observer);&lt;br /&gt;
Subject.setState(10);&lt;br /&gt;
// Output in console.log - 10&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
*[[Implicit invocation]]&lt;br /&gt;
*[[Client–server model]]&lt;br /&gt;
*The observer pattern is often used in the [[entity–component–system]] pattern&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
{{Reflist}}&lt;br /&gt;
&lt;br /&gt;
==External links==&lt;br /&gt;
*{{Wikibooks-inline|Computer Science Design Patterns|Observer|Observer implementations in various languages}}&lt;br /&gt;
&lt;br /&gt;
{{Design Patterns Patterns}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Software design patterns]]&lt;br /&gt;
[[Category:Articles with example Java code]]&lt;br /&gt;
[[Category:Articles with example Python (programming language) code]]&lt;br /&gt;
[[Category:Articles with example C Sharp code]]&lt;/div&gt;</summary>
		<author><name>~2025-30963-97</name></author>
	</entry>
</feed>