Friday, June 7, 2013

Observer Design Patterns - Behavioral Patterns in C#

Observer: Allows a single object to notify many dependent objects that its state has changed.

* Define a one-to-many dependency between objects so that when one object changes state,

     *   all its dependents are notified and updated automatically.

class Program
    {
        static void Main(string[] args)
        {
            ConcreteSubject s = new ConcreteSubject();

            s.Attach(new ConcreteObserver(s, "x"));
            s.Attach(new ConcreteObserver(s, "y"));
            s.Attach(new ConcreteObserver(s, "z"));

            s.SubjectState = "abc";
            s.Notify();
            Console.ReadKey();
        }
    }

    abstract class Observer
    {
        public abstract void Update();
    }
    abstract class Subject
    {
        private List<Observer> _observer = new List<Observer>();
        public void Attach(Observer observer)
        {
            _observer.Add(observer);
        }
        public void Detach(Observer observer)
        {
            _observer.Remove(observer);
        }
        public void Notify()
        {
            foreach (Observer o in _observer)
            {
                o.Update();
            }
        }
    }

    class ConcreteObserver : Observer
    {
        private string _name;
        private string _observerState;
        private ConcreteSubject _subject;

        public ConcreteObserver(ConcreteSubject subject, string name)
        {
            _subject = subject;
            _name = name;
        }

        public ConcreteSubject Subject
        {
            get { return _subject; }
            set { _subject = value; }
        }

        public string ObserverState
        {
            get { return _observerState; }
            set { _observerState = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }


        public override void Update()
        {
            _observerState = _subject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
        }
    }
    class ConcreteSubject : Subject
    {
        private string _subjectState;

        public string SubjectState
        {
            get { return _subjectState; }
            set { _subjectState = value; }
        }

    }

No comments:

Post a Comment