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!
===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>
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)