Click here to Skip to main content
6,594,432 members and growing! (16,742 online)
Email Password   helpLost your password?
Desktop Development » Dialogs and Windows » General     Beginner License: The Code Project Open License (CPOL)

Implement Observer Pattern in absolutely easy example

By Ng. Anh Vu

Observer pattern in C# using Event and Delegate
C# (C# 1.0, C# 2.0, C# 3.0), Windows (WinXP, Win2003), .NET (.NET 2.0), Win32, Visual Studio (VS2005, VS2008), Architect, Dev, Design
Posted:16 Sep 2008
Views:12,080
Bookmarked:22 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
20 votes for this article.
Popularity: 3.61 Rating: 2.78 out of 5
7 votes, 35.0%
1
3 votes, 15.0%
2
2 votes, 10.0%
3
1 vote, 5.0%
4
7 votes, 35.0%
5
pic11.JPG

Introduction

When you develope your application. I'm sure that you have to handler many many objects.
So If them have to interact with the same source data, I think that you must find a way to make them update with the change of data. Observer pattern is the key you can use for this solution!

Background 

I have searched this website and found a little article talk about observer pattern. And I have read some article about event and delegate, too. So that I want to show you - the new developers the way to implement observer pattern in the easiest way, faster way, and easiest to understand. 

Now, let's start!

Using the code 

I created a example in winforms, using C# language in .NET Framework 2.0.

  • I have 2 form: Form2 and Form3

  • In form2 there are 3 radio buttons, a Label and a Buttons. If you check the radio button you'll see that the fore color of label will be change with the color is the name of that radio button. It's very easy, isn't it?
  • When you click on button to open child form. Form3 will show! If you check the radio button again. Beside the fore color of label change, you'll see that the backcolor of textbox in Form3 will be changed too! That's it! 
  • I have 2 object in this solution:
    • Subject: It' will be the parent! When a client is created! the client must be register with this subject. When something change, the subject will notify to all the clients it manage to make them update
    • Observer: It's a client, when it was born, It' have to register with subject and waitting to update if there's something change. 

Subject Object  

first, I create a delegate and an event to make it can be "alive" when there's something change it!

private delegate void NotifyHandler(string _color);
private event NotifyHandler NotifyEvent;  

I also create a ArrayList names arrObs to manage all client object when it register to Subject object

ArrayList arrObs = new ArrayList();
 

The full details of subject is here: 

public class Subject
{
   ArrayList arrObs = new ArrayList();
   private delegate void NotifyHandler(string _color);
   private event NotifyHandler NotifyEvent;

   public Subject()
   {
      this.NotifyEvent += new NotifyHandler(Notify);
   }

   public void UpdateClient(string _color)
   {
       OnNotify(_color);
   }

   private void OnNotify(string _color)
   {
       if (NotifyEvent != null)
       {
           NotifyEvent(_color);
       }
   }

   private void Notify(string _color)
   {
       for (int i = 0; i < arrObs.Count; i++)
       {
           Observer obs = (Observer)arrObs[i];
           obs.Update(_color);
       }
   }
     
   public void RegisterClient(Observer obs)
   {
       arrObs.Add(obs);
   }
}

You will see that when the subject is created, it's will register the NotifyEvent with Notify method. In the Notify(), it pass the _color string to all the client in arrObs. And clients will call Update method to update the color.

Now, let's see the client object names Observer!

Observer Object

Same to Subject object, I will define a delegate and an event to make it alive when subject notify them!

private delegate void ColorEventHandler(string _color);
private event ColorEventHandler ColorChangedEvent;  

Like the subject, when subject notify to observer (in Update method above), the ColorChangedEvent will be fired and call ColorEventHander to pass the _color string to update!

In this solution, I want to update the back color of Form3. So, this observer object will be created in form3 and pass the textbox object to observer in contructor:

private TextBox txt;
public Observer(TextBox _txt)
{
     this.ColorChangedEvent += new ColorEventHandler(Observer_ColorChangedEvent);
     this.txt = _txt;
}  

 

The full detail of Observer object will be here:

public class Observer
{
    private delegate void ColorEventHandler(string _color);
    private event ColorEventHandler ColorChangedEvent;
    private TextBox txt;
    
    public Observer(TextBox _txt)
    {
        this.ColorChangedEvent += new ColorEventHandler(Observer_ColorChangedEvent);
        this.txt = _txt;
    }

    private void OnChange(string _color)
    {
        if (ColorChangedEvent != null)
        {
            ColorChangedEvent(_color);
        }
    }
    
    public void Update(string _color)
    {
        OnChange(_color);
    }
  
    private void Observer_ColorChangedEvent(string _color)
    {
        switch (_color)
        { 
            case "RED":
                txt.BackColor = Color.Red;
                break;
            case "BLUE":
                txt.BackColor = Color.Blue;
                break;
            case "GREEN":
                txt.BackColor = Color.Green;
                break;
            default: 
                txt.BackColor = Color.Gray;
                break;
        }
    }
} 

 Form2

When radio button is checked changed! It will call the Subject object to update its client

private void rdRed_CheckedChanged(object sender, EventArgs e)
{
      if (rdRed.Checked)
      {
          objSub.UpdateClient("RED");
          lblText.ForeColor = Color.Red;                
      }
 }

 private void rdGreen_CheckedChanged(object sender, EventArgs e)
 {
       if (rdGreen.Checked)
       {
           objSub.UpdateClient("GREEN");
           lblText.ForeColor = Color.Green;
       }
 }

 private void rdBlue_CheckedChanged(object sender, EventArgs e)
 {
       if (rdBlue.Checked)
       {
           objSub.UpdateClient("BLUE");
           lblText.ForeColor = Color.Blue;
       }
  }

When click on Button to create and open Form3, There is a subject object name objSub was created in form and and pass to form3 through constructor:

private Subject objSub;
private Form3 frm;
public Form2()
{
     InitializeComponent();
     objSub = new Subject();
}        

private void btnOpen_Click(object sender, EventArgs e)
{
     frm = new Form3(objSub);
     frm.Show();
} 

Form3

Only create a new observer object and register it with the objSub

public Form3(Subject _objSub)
{
     InitializeComponent();
     objSub = _objSub;
     obs = new Observer(this.textBox1);
     objSub.RegisterClient(obs);
}

That's all! When you click on the radio button, it's will call the subject to update clients in its arraylist. The client wil be notified and update the background of textbox with the color pass through by the subject.

Points of Interest 

It's a compact of implement observer pattern in an easy example! Hope you can understand and learn how to solve you problem from this small example! 

Feel free when contact to me!

Name: Nguyen Anh Vu(Mr.)
Email: vuna209@gmail.com
Mobile: +84984886940
Addr: 7 floor, 53 Quang Trung, Hanoi, VietNam.

License

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

About the Author

Ng. Anh Vu


Member

Occupation: Web Developer
Location: Vietnam Vietnam

Other popular Dialogs and Windows articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
Generalit works ok with the textbox but not with the listbox Pinmembernipsonanomimata22:49 2 Oct '09  
GeneralRe: it works ok with the textbox but not with the listbox Pinmembernipsonanomimata1:02 3 Oct '09  
GeneralGood article [modified] PinmemberDonsw15:50 21 Jan '09  
Generalvery good PinmemberDearMadalin16:40 22 Sep '08  
QuestionWhy so complicated? Pinmemberptmcomp10:19 22 Sep '08  
AnswerRe: Why so complicated? Pinmemberspiderman_anhvu18:30 22 Sep '08  
GeneralRe: Why so complicated? Pinmemberfire_birdie20:49 22 Sep '08  
GeneralRe: Why so complicated? Pinmemberspiderman_anhvu22:19 22 Sep '08  
GeneralRe: Why so complicated? Pinmemberfire_birdie22:50 22 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Sep 2008
Editor: Sean Ewington
Copyright 2008 by Ng. Anh Vu
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project