Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Observer pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example== <!-- 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 --> While the library classes [https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Observer.html <code>java.util.Observer</code>] and [https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Observable.html <code>java.util.Observable</code>] exist, they have been [[Deprecation|deprecated]] in Java 9 because the model implemented was quite limited. 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 <code>System.in</code>, the method <code>notifyObservers()</code> 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=== <syntaxhighlight lang="java"> import java.util.ArrayList; import java.util.List; import java.util.Scanner; interface Observer { void update(String event); } class EventSource { List<Observer> 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.println("Received response: " + event)); eventSource.scanSystemIn(); } } </syntaxhighlight> ===C++=== This is a C++11 implementation. <syntaxhighlight lang="c++"> #include <functional> #include <iostream> #include <list> class Subject; //Forward declaration for usage in Observer class Observer { public: explicit Observer(Subject& subj); virtual ~Observer(); Observer(const Observer&) = delete; // rule of three Observer& operator=(const Observer&) = delete; virtual void update( Subject& s) const = 0; private: // Reference to a Subject object to detach in the destructor Subject& subject; }; // Subject is the base class for event generation class Subject { public: using RefObserver = std::reference_wrapper<const Observer>; // Notify all the attached observers void notify() { for (const auto& x: observers) { x.get().update(*this); } } // Add an observer void attach(const Observer& observer) { observers.push_front(observer); } // Remove an observer void detach(Observer& observer) { observers.remove_if( [&observer ](const RefObserver& obj) { return &obj.get()==&observer; }); } private: std::list<RefObserver> observers; }; Observer::Observer(Subject& subj) : subject(subj) { subject.attach(*this); } Observer::~Observer() { subject.detach(*this); } // Example of usage class ConcreteObserver: public Observer { public: ConcreteObserver(Subject& subj) : Observer(subj) {} // Get notification void update(Subject&) const override { std::cout << "Got a notification" << std::endl; } }; int main() { Subject cs; ConcreteObserver co1(cs); ConcreteObserver co2(cs); cs.notify(); } </syntaxhighlight> The program output is like <syntaxhighlight lang="c++"> Got a notification Got a notification </syntaxhighlight> ===Groovy=== <syntaxhighlight lang="groovy"> class EventSource { private observers = [] private notifyObservers(String event) { observers.each { it(event) } } void addObserver(observer) { observers += observer } void scanSystemIn() { var scanner = new Scanner(System.in) while (scanner) { var line = scanner.nextLine() notifyObservers(line) } } } println 'Enter Text: ' var eventSource = new EventSource() eventSource.addObserver { event -> println "Received response: $event" } eventSource.scanSystemIn() </syntaxhighlight> ===Kotlin=== <syntaxhighlight lang="kotlin"> import java.util.Scanner typealias Observer = (event: String) -> Unit; class EventSource { private var observers = mutableListOf<Observer>() private fun notifyObservers(event: String) { observers.forEach { it(event) } } fun addObserver(observer: Observer) { observers += observer } fun scanSystemIn() { val scanner = Scanner(System.`in`) while (scanner.hasNext()) { val line = scanner.nextLine() notifyObservers(line) } } } </syntaxhighlight> <syntaxhighlight lang="kotlin"> fun main(arg: List<String>) { println("Enter Text: ") val eventSource = EventSource() eventSource.addObserver { event -> println("Received response: $event") } eventSource.scanSystemIn() } </syntaxhighlight> ===Delphi=== <syntaxhighlight lang="delphi"> uses System.Generics.Collections, System.SysUtils; type IObserver = interface ['{0C8F4C5D-1898-4F24-91DA-63F1DD66A692}'] procedure Update(const AValue: string); end; type TObserverManager = class private FObservers: TList<IObserver>; 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[i].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; </syntaxhighlight> Output <pre> Husband listener received notification: Someone is knocking on the door Wife listener received notification: Someone is knocking on the door </pre> ===Python=== A similar example in [[Python_(programming_language)|Python]]: <syntaxhighlight lang="python"> class Observable: def __init__(self): self._observers = [] def register_observer(self, 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.register_observer(self) def notify(self, observable, *args, **kwargs) -> None: print("Got", args, kwargs, "From", observable) subject = Observable() observer = Observer(subject) subject.notify_observers("test", kw="python") # prints: Got ('test',) {'kw': 'python'} From <__main__.Observable object at 0x0000019757826FD0> </syntaxhighlight> ===C#=== C# provides the {{Code|IObservable}}.<ref>{{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}}</ref> and {{Code|IObserver}}<ref>{{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}}</ref> interfaces as well as documentation on how to implement the design pattern.<ref>{{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}}</ref> <syntaxhighlight lang="csharp"> class Payload { internal string Message { get; set; } } class Subject : IObservable<Payload> { private readonly ICollection<IObserver<Payload>> _observers = new List<IObserver<Payload>>(); IDisposable IObservable<Payload>.Subscribe(IObserver<Payload> observer) { if (!_observers.Contains(observer)) { _observers.Add(observer); } return new Unsubscriber(observer, _observers); } internal void SendMessage(string message) { foreach (var observer in _observers) { observer.OnNext(new Payload { Message = message }); } } } internal class Unsubscriber : IDisposable { private readonly IObserver<Payload> _observer; private readonly ICollection<IObserver<Payload>> _observers; internal Unsubscriber( IObserver<Payload> observer, ICollection<IObserver<Payload>> observers) { _observer = observer; _observers = observers; } void IDisposable.Dispose() { if (_observer != null && _observers.Contains(_observer)) { _observers.Remove(_observer); } } } internal class Observer : IObserver<Payload> { internal string Message { get; set; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(Payload value) { Message = value.Message; } internal IDisposable Register(IObservable<Payload> subject) { return subject.Subscribe(this); } } </syntaxhighlight> ===JavaScript=== JavaScript has a deprecated {{code|Object.observe}} function that was a more accurate implementation of the observer pattern.<ref>{{Cite web|url=https://stackoverflow.com/a/50862441/887092|title = jQuery - Listening for variable changes in JavaScript}}</ref> 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:<ref>{{Cite web|url=https://stackoverflow.com/a/37403125/887092|title = Jquery - Listening for variable changes in JavaScript}}</ref> <syntaxhighlight lang="js"> 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 < this._observers.length; i++) { this._observers[i].signal(this); } } }; let Observer = { signal: function(subject) { let currentValue = subject.getState(); console.log(currentValue); } } Subject.add(Observer); Subject.setState(10); //Output in console.log - 10 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)