Click here to Skip to main content
15,891,033 members
Articles / Programming Languages / C#
Tip/Trick

The Observer Pattern

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
19 Feb 2013CPOL 10K   214   3
The "Observer Pattern" defines a One-To-Many dependency between objects.

Introduction

The "Observer Pattern" defines a One-To-Many dependency between objects.

when one object changes state, all of its dependentsare notified and updated automatically.


ONE Subject to the MANY Observers !!!!
Subject can be anything which interests Observers.
Observers are objects who are interested in some Subject.

EXAMPLE : Newpaper Subscription where "Newspaper is Subject" and "Subscribers are Observers".
          ONE Newspaper to MANY Subscribers.

Background

Design Principal  : Strive for loosely coupled designs between objects that interact.

Loosely coupled designs allow us to build flexible system that can handle changes becoz they minimize interdependency.


Note : Observer Pattern can be implemented using Events & Delegates in .Net, .Net 4.0 has now IObservable & IObserver interfaces to facilitate the Observer Pattern.
This Example has implementations using Custom Interface & .Net in-house IObservable interface.

Using the code

// Custom IObserver Interface

C#
public interface IObserver
{
    void Update(float temp, float hum, float press);
}

 // Observer Class which Observes or Subscribe from Observable Data

C#
public class CurrentConditionsDisplay : IObserver,IDisplayElement
{
    private float temperature;
    private float humidity;
    private ISubject weatherData;

    public CurrentConditionsDisplay(ISubject weatherData)
    {
        this.weatherData = weatherData;
        if(weatherData != null)
            weatherData.RegisterObserver(this);
    }

    public void RemoveObservation()
    {
        weatherData.RemoveObserver(this);
    }

    public void Update(float temp, float hum, float press)
    {
        this.temperature = temp;
        this.humidity = hum;
        Display();
    }

    public void Display()
    {
        Console.WriteLine("Current Conditions: " + temperature + "F Degrees and " + humidity + "% Humidity");
    }
}

 

// Custom IObservable Interface

C#
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void RemoveObserver(IObserver observer);
    void NotifyObservers();
}

 

// Observable class which can be observed by Observer Class

C#
public class WeatherData : ISubject
{
    private ArrayList Observers;
    private float _temperature;
    private float _humidity;
    private float _pressure;

    public WeatherData()
    {
        Observers = new ArrayList();
    }

    #region ISubject Members

    public void RegisterObserver(IObserver observer)
    {
        Observers.Add(observer);
    }

    public void RemoveObserver(IObserver observer)
    {
        int i = Observers.IndexOf(observer);
        if (i >= 0)
        {
            Observers.Remove(observer);
        }
    }

    public void NotifyObservers()
    {
        foreach (IObserver o in Observers)
        {
            o.Update(_temperature, _humidity, _pressure);
        }
    }

    #endregion

    public void MeasurementChanged()
    {
        NotifyObservers();
    }

    public void SetMeasurements(float temperature, float humidity, float pressure)
    {
        this._temperature = temperature;
        this._humidity = humidity;
        this._pressure = pressure;
        MeasurementChanged();
    }
}

Points of Interest

This Pattern can be implemented by directly using IObserver<T> & IObservable<T> provided by .Net Library also, attached code includes implementation with .Net in-house interface as well.

History

Version 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ABB
India India
Working in Software Development since 2007.
Work in .Net/VC++/COM.
work in Process Automation domain.

Comments and Discussions

 
Question[My vote of 1] My vote of 1. Pin
r v19-Feb-13 4:01
r v19-Feb-13 4:01 
Mad | :mad: This code is effectively a direct cut/paste/translate from the JAVA code contained in the O'Reilly book "Head First Design Patterns" for the Observer pattern. Even the variable names are effectively the same.

You can download the code from http://www.headfirstlabs.com/books/hfdp/[^] and then look under HF_DP/src/headfirst/observer/weather after you've unzipped the file.

I read the book a while back and could never understand why they used such a contrived example for the Observer pattern, and so when I saw this code, it hit the same nerve. A little bit of Google on "public class WeatherData" verified my suspicion, and then hunting down my copy of the book proved it.
AnswerRe: [My vote of 1] My vote of 1. Pin
Chandra Shekhar Joshi19-Feb-13 15:03
Chandra Shekhar Joshi19-Feb-13 15:03 
QuestionNot an article Pin
OriginalGriff18-Feb-13 23:05
mveOriginalGriff18-Feb-13 23:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.