6 July 2007

The Observer Pattern

by mo

“The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.” - Head First Design Patterns

What this means is that if you have objects that are interested in changes in another object, you allow the “observers” to register or subscribe to the subject. In the example provided, my wife and mother in law want to be notified whenever i look at cute girls. Each time i look at a cute girl they should be notified and then they can take whatever action they want.

Typically, you would push or pull the data from the subject (that’s me), to the observers (that’s my wife and her mom). Mo (that’s me) contains an internal list of relatives that want to know what he’s up to. Anytime one of his relatives wants to check in on him, the add themselves to Mo’s interal list. If they’re no longer interested, they can remove themselves for the internal list.

  public Mo( IList< IObserver > concernedRelatives ) {
    _concernedRelatives = concernedRelatives;
    LookAtCuteGirl += delegate { OnLookedAtCuteGirl( ); };

  public event EventHandler LookAtCuteGirl;

  public void Add( IObserver observer ) {
    _concernedRelatives.Add( observer );

  public void Remove( IObserver observer ) {
    _concernedRelatives.Remove( observer );

  private IList< IObserver > _concernedRelatives;

  private void OnLookedAtCuteGirl( ) {
    foreach ( IObserver relative in _concernedRelatives ) {
      relative.Update( );

Let’s say my wife is concerned and wants to check up on me, here’s how she would do it.

  public MosWife(ISubject husband) {
    _husband = husband;

  public void Update() {
    Console.Out.WriteLine("Why is my husband looking at cute girls?");

  private ISubject _husband;

She’s decided to always add her self to my internal list to see what I’m doing. If I should happen to check out a cute girl, she will be immediately notified. Lucky for me, my wife is pretty laid back, and asks herself “Why is my husband looking at cute girls?”…

Hopefully, this helps to demonstrate the observer pattern. I realize that it is rather contrived example, and the source could could be refactored. But hopefully it’s clear.

For a better explanation, you should read…

Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra Read more about this title…

P.S. My wife does not check up on me, she’s awesome! DesignPatterns.Observer.zip (4.01 KB)

books csharp designpatterns