Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Observer

Subject broadcasts state changes to observers.

C#

// Observer interface
interface IObs
{
	void Update(int v);
}

// Subject maintains list of observers
class Subject
{
	private readonly List _observers = new();
	private int _state;
	public void Attach(IObs o) => _observers.Add(o);
	public void Set(int v)
	{
		_state = v;
		foreach (var o in _observers)
			o.Update(_state);
	}
}

// Concrete observer
class PrintObs : IObs
{
	public void Update(int v) => Console.WriteLine("val=" + v);
}

// Usage
var subject = new Subject();
subject.Attach(new PrintObs());
subject.Set(5);
next