Observer Design Pattern

Hi,


Many times when programming we come across situation where by change in one change needs to be updated in multiple object. For example if a parameter is used to make multiple calculation in different objects then on change of that parameter all the objects need to be notified of the change.  Or for example when the windows (operating system) or Dot Net framework shut downs or closes then it notifies all the application running on it to close so that it can make a clean close.

 

For this kind of situation the observer pattern was designed. In observer pattern there is a subject (also called observer) which maintains the list of all the dependent objects. In case of any change all the dependent objects are notified with the help of a call to one of the method. This is mainly helpful in distributed event handling. It creates a One 2 many relationships between the subject and the dependent objects (also called listener).

 

Normally the Subject (Observer is defined like the one below)

abstract class aSubject

    {

        private List<IObserver> observers = new List<IObserver>();

 

        // Abstract PropertyThe change of this property will be notified to the observer
        Public string strText

 

        public void Attach(IObserver observer)

        {

            observers.Add(observer);

        }

 

        public void Detach(IObserver observer)

        {

            observers.Remove(observer);

        }

 

        public void Notify()

        {

            foreach (IObserver o in observers)

            {

                o.Update();

            }

        }

    }

 

The abstract interface is very simple with only one method

All the observer class will have to implement this method and will receive the notification with the call to this method. If required the Observer class might also raise an event inside the implementation of the Update method.

     interface IObserver
    {
        // this method will be called on change of the property

        void Update();

    }

 

 

The abstract subject class does most of the work. The actual Subject (concrete class will have only one small work of calling the Notify method on change of the property.)

  class ConcreteSubject : Subject

    {

        public string _strText;

 

        public string strText

        {

            get

            {

                return _strText;

            }

            set

            {

                _strText = value;              
                // Call the Notify method to update all the observer

                Notify();

            }

        }

    }

 

The concrete Observer looks something like this.

  class ConcreteObserver : IObserver

    {

        // Other Implementation of class

        public void Update()

        {

            Console.WriteLine(“Notified”);

        }

    }

 

Vikram

3 Comments

Comments have been disabled for this content.