Observer Pattern

Published by

on

The Observer Pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

For the sake of simplicity we could visualise the subject as an observable that other observers look at for an Update.

Let’s take an example of a weather station that sends out weather update to various news stations/channels.

using System;
using System.Collections.Generic;

namespace ObserverPattern
{
    public interface WeatherSubject
    {
        void addObserver(WeatherObserver weatherObserver);
        void removeObserver(WeatherObserver weatherObserver);
        void doNotify();
    }

    public interface WeatherObserver
    {
        void doUpdate(int temperature);
    }

    ///<summary>
    /// SUBJECT: Single Weather station that collects weather Data
    /// </summary>

    public class WeatherStation : WeatherSubject
    {
        List weatherObservers;
        int temperature;

        public WeatherStation(int temperature)
        {
            weatherObservers = new List();
            this.temperature = temperature;
        }

        public void addObserver(WeatherObserver weatherObserver)
        {
            weatherObservers.Add(weatherObserver);
        }

        public void removeObserver(WeatherObserver weatherObserver)
        {
            weatherObservers.Remove(weatherObserver);
        }

        public void doNotify()
        {
            foreach (WeatherObserver wo in weatherObservers)
            {
                wo.doUpdate(temperature);
            }
        }

        public void setTemperature(int newTemperature)
        {
            Console.WriteLine("\nWeather station setting temperature to " + newTemperature);
            temperature = newTemperature;
            doNotify();
        }

    }

    public class WeatherCustomer1 : WeatherObserver
    {
        public void doUpdate(int temperature)
        {
            Console.WriteLine("Weather customer 1 found out temp  is:" + temperature);
        }
    }

    public class WeatherCustomer2 : WeatherObserver
    {
        public void doUpdate(int temperature)
        {
            Console.WriteLine("Weather customer 2 found out temp is:" + temperature);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WeatherStation weatherStation = new WeatherStation(33);

            WeatherCustomer1 wc1 = new WeatherCustomer1();
            WeatherCustomer2 wc2 = new WeatherCustomer2();
            weatherStation.addObserver(wc1);
            weatherStation.addObserver(wc2);

            weatherStation.setTemperature(34);
            weatherStation.removeObserver(wc1);
            weatherStation.setTemperature(35);
        }
    }
}

/*Output:
 * Weather station setting temperature to 34
 * Weather customer 1 just found out the temperature is:34
 * Weather customer 2 just found out the temperature is:34
 * Weather station setting temperature to 35
 * Weather customer 2 just found out the temperature is:35
*/

Code walkthrough might not be needed in the above case.

WeatherSubject is the Observable that all Observers (WeatherCustomer1… ) observe for any changes in temperature. Observer pattern removes the need for the clients to poll the Subject/Observable at a regular interval for any changes. This in-turn reduces the idle time for a client.

Advantages of this design :

  • Iff there is a change in value all the clients subscribed to the Subject are notified.
  • Any number of Observers can be added/removed with no changes to Subject/Observable needed.
  • The Observer only needs to register once and is not blocked trying to poll for changes from Server/Subject.
  • Any given time Observer has the freedom to unsubscribe to updates from the Subject/Observable.

Uses in real life:

  • GUI development : I personally used them a lot when I was created UI for games. Imagine when there is a power up , it needs to notified on the user screen and also game logic needs to be updated at several places. This pattern works beautifully !
  • RSS feeds , email subscription. Anything that needs PUSH Notifications.
  • All users of an App on Google play store get notified when there is an in-App update
Previous Post
Next Post