HOME

TheInfoList



OR:

In
software design Software design is the process by which an agent creates a specification of a software artifact intended to accomplish goals, using a set of primitive components and subject to constraints. Software design may refer to either "all the activi ...
and
engineering Engineering is the use of scientific principles to design and build machines, structures, and other items, including bridges, tunnels, roads, vehicles, and buildings. The discipline of engineering encompasses a broad range of more speciali ...
, the observer pattern is a
software design pattern In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine ...
in which an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
. It is often used for implementing distributed event-handling systems in event-driven software. In such systems, the subject is usually named a "stream of events" or "stream source of events" while the observers are called "sinks of events." The stream nomenclature alludes to a physical setup in which the observers are physically separated and have no control over the emitted events from the subject/stream source. This pattern thus suits any process by which data arrives from some input that is not available to the
CPU A central processing unit (CPU), also called a central processor, main processor or just processor, is the electronic circuitry that executes instructions comprising a computer program. The CPU performs basic arithmetic, logic, controlling, a ...
at startup, but instead arrives seemingly at random ( HTTP requests, GPIO data, user input from
peripheral A peripheral or peripheral device is an auxiliary device used to put information into and get information out of a computer. The term ''peripheral device'' refers to all hardware components that are attached to a computer and are controlled by the ...
s, distributed databases and
blockchain A blockchain is a type of distributed ledger technology (DLT) that consists of growing lists of records, called ''blocks'', that are securely linked together using cryptography. Each block contains a cryptographic hash of the previous block, ...
s, etc.). Most modern
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s comprise built-in event constructs implementing the observer-pattern components. While not mandatory, most observer implementations use background threads listening for subject events and other support mechanisms provided by the kernel.


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.


Which problems can the observer design pattern solve?

The observer pattern addresses the following problems: * 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. Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible because it couples the subject to particular dependent objects. However, it might be applicable from a performance point of view or if the object implementation is tightly coupled (such as low-level kernel structures that execute thousands of times per second). Tightly coupled objects can be difficult to implement in some scenarios and are not easily reused because they refer to and are aware of many objects with different interfaces. In other scenarios, tightly coupled objects can be a better option because the compiler is able to detect errors at compile time and optimize the code at the CPU instruction level.


What solution does the Observer design pattern describe?

* Define Subject and Observer objects. * When a subject changes state, all registered observers are notified and updated automatically (and probably asynchronously). The sole responsibility of a subject is to maintain a list of observers and to notify 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 their state with the subject's state) when they are notified. This makes subject and observers loosely coupled. Subject and observers have no explicit knowledge of each other. Observers can be added and removed independently at run time. This notification-registration interaction is also known as publish-subscribe.


Strong vs. weak reference

The observer pattern can cause
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 object ...
s, known as the
lapsed listener problem In computer programming, the lapsed listener problem is a common source of memory leaks for object-oriented programming languages, among the most common ones for garbage collected languages.dispose pattern, because the subject holds strong references to the observers, keeping them alive. This can be prevented if the subject holds weak references to the observers.


Coupling and typical publish-subscribe implementations

Typically, the observer pattern is implemented so that the subject being observed is part of the object for which state changes are being observed (and communicated to the observers). This type of implementation is considered tightly coupled, forcing both the observers and the subject to be aware of each other and have access to their internal parts, creating possible issues of
scalability Scalability is the property of a system to handle a growing amount of work by adding resources to the system. In an economic context, a scalable business model implies that a company can increase sales given increased resources. For example, a ...
, speed, message recovery and maintenance (also called event or notification loss), the lack of flexibility in conditional dispersion and possible hindrance to desired security measures. In some ( non-polling) implementations of the publish-subscribe pattern, this is solved by creating a dedicated message queue server (and sometimes an extra message handler object) as an extra stage between the observer and the object being observed, thus decoupling the components. In these cases, the message queue server is accessed by the observers with the observer pattern, subscribing to certain messages and knowing (or not knowing, in some cases) about only the expected message, while knowing nothing about the message sender itself; the sender may also know nothing about the observers. Other implementations of the publish-subscribe pattern, which achieve a similar effect of notification and communication to interested parties, do not use the observer pattern. In early implementations of multi-window operating systems such as
OS/2 OS/2 (Operating System/2) is a series of computer operating systems, initially created by Microsoft and IBM under the leadership of IBM software designer Ed Iacobucci. As a result of a feud between the two companies over how to position OS/2 r ...
and
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for se ...
, the terms "publish-subscribe pattern" and "event-driven software development" were used as synonyms for the observer pattern. The observer pattern, as described in the ''Design Patterns'' book, is a very basic concept and does not address removing interest in changes to the observed subject or special logic to be performed by the observed subject before or after notifying the observers. The pattern also does not deal with recording change notifications or guaranteeing that they are received. These concerns are typically handled in message-queueing systems, in which the observer pattern plays only a small part. Related patterns include publish–subscribe,
mediator Mediator may refer to: *A person who engages in mediation * Business mediator, a mediator in business * Vanishing mediator, a philosophical concept * Mediator variable, in statistics Chemistry and biology *Mediator (coactivator), a multiprotein ...
and singleton.


Uncoupled

The observer pattern may be used in the absence of publish-subscribe, as when model status is frequently updated. Frequent updates may cause the view to become unresponsive (e.g., by invoking many
repaint A repaint is a toy, typically a figure or doll, that was created entirely from a mold was previously available; however, the colors of the plastic and/or the paint operations have been changed. Repaints differ from redecos in that repaints do not ...
calls); such observers should instead use a timer. Instead of becoming overloaded by change message, the observer will cause the view to represent the approximate state of the model at a regular interval. This mode of observer is particularly useful for progress bars, in which the underlying operation's progress changes frequently.


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 rela ...
, 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 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 In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing ...
in Java 9 because the model implemented was quite limited. Below is an example written in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
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.List; import java.util.ArrayList; import java.util.Scanner; class EventSource public class ObserverDemo


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: class Observable: def __init__(self): self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self, *args, **kwargs): for obs in self._observers: obs.notify(self, *args, **kwargs) class Observer: def __init__(self, observable): observable.register_observer(self) def notify(self, observable, *args, **kwargs): 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>


C#

public class Payload public class Subject : IObservable public class Unsubscriber : IDisposable public class Observer : IObserver


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 Implicit invocation is a term used by some authors for a style of software architecture in which a system is structured around event handling, using a form of callback. It is closely related to inversion of control and what is known informally a ...
*
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 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