Class ObserverPattern<T>
- Namespace
- WitShells.DesignPatterns.Core
A lightweight, generic implementation of the Observer pattern. Maintains a list of subscriber callbacks and notifies them all when a value is published. Prefer this over C# events when you need runtime subscribe/unsubscribe with no delegate leak risk, or when you want to store the observer list as a field rather than as a static event.
public class ObserverPattern<T>
Type Parameters
TThe type of data passed to each observer when notified.
- Inheritance
-
ObserverPattern<T>
- Inherited Members
Examples
var onHealthChanged = new ObserverPattern<int>();
onHealthChanged.Subscribe(hp => Debug.Log($"HP: {hp}"));
onHealthChanged.NotifyObservers(50);
Methods
NotifyObservers(T)
Invokes all registered observer callbacks with the supplied value. Null callbacks are skipped safely.
public void NotifyObservers(T value)
Parameters
valueTThe data to broadcast to every observer.
Subscribe(Action<T>)
Registers a callback as an observer. Duplicate subscriptions are ignored.
public void Subscribe(Action<T> observer)
Parameters
observerAction<T>The callback to invoke when a notification is broadcast.
Unsubscribe(Action<T>)
Removes a previously registered observer callback.
public void Unsubscribe(Action<T> observer)
Parameters
observerAction<T>The callback to remove.