November 14, 2010 by Christoff Truter C# Design Patterns Architecture
The observer pattern is basically a process where the change in an object's state (e.g. assignment of a property), must notify a list of dependant objects
on that change.
interface IObserver { void Update(Object subject); } abstract class Observable { protected List<IObserver> container = new List<IObserver>(); public void Attach(IObserver observer) { container.Add(observer); } public void Detach(IObserver observer) { container.Remove(observer); } protected void Notify() { foreach (IObserver observer in container) { observer.Update(this); } } }
class Beacon : Observable { private bool _IsLit; public bool IsLit { get { return _IsLit; } set { _IsLit = value; this.Notify(); } } } class Observer : IObserver { private string _name; public Observer(string name) { _name = name; } public void Update(Object subject) { Beacon beacon = (Beacon)subject; Console.WriteLine("Beacon at {0} {1}", _name, (beacon.IsLit) ? "lit" : "not lit"); } }
static void Main(string[] args) { Beacon beacon = new Beacon(); beacon.Attach(new Observer("Amon Dîn")); beacon.Attach(new Observer("Eilenach")); beacon.Attach(new Observer("Nardol")); beacon.Attach(new Observer("Erelas")); beacon.Attach(new Observer("Min-Rimmon")); beacon.Attach(new Observer("Calenhad")); beacon.Attach(new Observer("Halifirien")); beacon.IsLit = true; }
class Beacon : List<string> { public event Action<Beacon> onLit; private bool _IsLit; public bool IsLit { get { return _IsLit; } set { _IsLit = value; if (onLit != null) { onLit(this); } } } } class Program { static void Main(string[] args) { Beacon beacon = new Beacon(); beacon.onLit += new Action<Beacon>(beacon_onLit); beacon.Add("Amon Dîn"); beacon.Add("Eilenach"); beacon.Add("Nardol"); beacon.Add("Erelas"); beacon.Add("Min-Rimmon"); beacon.Add("Calenhad"); beacon.Add("Halifirien"); beacon.IsLit = true; } static void beacon_onLit(Beacon obj) { foreach (string name in obj) { Console.WriteLine("Beacon at {0} {1}", name, (obj.IsLit) ? "lit" : "not lit"); } } }