Sunday, August 5, 2012

Observer pattern

In this design pattern, the subject has a list of objects that are dependent on it. For a certain event, the subject informs the objects that the event has occurred. In computers, task scheduler is perfect example of the same.
Here is the C# implementation followed by its class diagram:
    public class Subject
    {
        public event ObserverEvent forObserver;
        private int sleepTime;
        public EventArgs e = null;
        public delegate void ObserverEvent(EventArgs e);
        public Subject() : this((new Random()).Next() % 10000)
        {
        }
        public Subject(int interval)
        {
            this.sleepTime = interval;
        }
        public void BeginWait()
        {
            System.Diagnostics.Debug.WriteLine("Adding 10 second sleep...");
            System.Threading.Thread.Sleep(10000);
            System.Diagnostics.Debug.WriteLine("Adding {0} millisecond sleep...", this.sleepTime);
            System.Threading.Thread.Sleep(this.sleepTime);
            System.Diagnostics.Debug.WriteLine("Waking all listeners");
            if (forObserver != null)
            {
                forObserver(e);
            }
        }
    }
    class Observer
    {
        public Observer()
        {
        }
        public void SubscribeToEvent(Subject s)
        {
            s.forObserver += new Subject.ObserverEvent(EventHandler);
        }
        private void EventHandler(EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Got the event handler");
        }
    }
 static void Main(string[] args)
        {
            Program pr = new Program();
            pr.UseSingleton();
            // Now use observer pattern
            // Create the observer
            Observer o1 = new Observer();
            Observer o2 = new Observer();
            // Creare the subject
            Subject s = new Subject();
           
            // Subscribe to event
            o1.SubscribeToEvent(s);
            o2.SubscribeToEvent(s);
            // Call back
            s.BeginWait();
        }

Following is the class diagram for the observer pattern:

No comments:

Post a Comment