?
Solved

Delegates and Events as component technology for GoF Observer pattern ?

Posted on 2006-04-17
5
Medium Priority
?
307 Views
Last Modified: 2008-03-17

I am a college student trying to build a small Windows Application in Visual Studio 2005.

Business Context:

Simulation of Computer science department that contains faculty, students, courses, programs, registration process etc.

My Question:

One aspect of the project requires me to simulate students enrolling/dropping classes, and the automatic notification to a faculty member when an enrollment is reached. Is delegates and events the best way to implement this in C# ? Does this involve a lot of code? Any good implementation strategies on this with respect to C# ?

Is there any good component technology that can be readily used to capture the Gang of Four Observer design pattern that can be applied to the above problem ?

Thanks.
0
Comment
Question by:scarface7
  • 4
5 Comments
 
LVL 6

Accepted Solution

by:
PoeticAudio earned 2000 total points
ID: 16475179
Actually the observer pattern is quite close to delegates/events. Events are extremely handy for de-coupling classes. One class raises an event and any class that has an event handler can respond to that event. Neither class really needs to know about eachother for this to take place. The class raising the event doesn't care what-if-any classes are registered, and the class that contains the event handler could care less either (ie: often times both classes can still function whether or not a class has an event handler setup or not) Of course there is a little bit of coupling because the class that contains the event handler must know something about the class that's raising the event, but the coupling is quite loose.

Here is an example of an event.

Let's start with a really simple example. Let's say we have a class that is called NumberCounter, and it has a method called CountToTen. Well, once it hits 10 we want to raise an event and let all other classes with event handlers wired to this event know that this class hit 10. Lets see the class.

public class NumberCounter
{
    //delegates hold references to methods. The delegate is the bridge between the event being
    //raised and the event handler. As long as the method signatures are the same, another class
    //can tie it's method (the event handler) into this delegate. A delegate is a special kind of object
    //so we declare an event of this delegate object. I suck at explaining things, sorry =)

    public delegate void OnCountedToTenEventHandler();
    public event OnCountedToTenEventHandler OnCountedToTen;

    public NumberCounter()
    {      
    }

    public void CountToTen()
    {
        for(int i = 0; i <= 10; i++)
        {
            if(i == 10)
            {
                //Once we hit 10 we raise the event, which will notify all the event handlers via
                //the delegate we declared above. Since the delegate holds a reference to all
                //methods (event handlers), all events that are tied in will be notified once the
                //count hits 10.
                OnCountedToTen();
            }
        }
    }
}



Alright. Now lets tie into this event from with another class.

//this object is class-wide scope
NumberCounter numberCounter = new NumberCounter();

public Form1()
{
    InitializeComponent();
    //here is where we tie it all together. Whenever NumberCounter's method CountToTen method hits ten
    //then we want to handle that event via numberCounter_OnCountedToTen method defined below
    numberCounter.OnCountedToTen += new
        WindowsApplication1.NumberCounter.OnCountedToTenEventHandler(numberCounter_OnCountedToTen);
}

//this is what we want to happen whenever NumberCounter's method CountToTen hits 10.
private void numberCounter_OnCountedToTen()
{
    MessageBox.Show("Number counter hit 10!");
}


I hope that all made sense to you. We define a delegate to hold references to methods. We define an event that gets raised, which in turn calls the delegate, which in turn calls all of the methods that are referenced in that delegate. I hope I explained all of this correctly =) It may seem a little confusing at first, but actually once it clicks it makes a lot of sense. I use events all the time! They are very similar to the observer pattern. In the observer pattern, the observer notifies all of the "subjects" when something interesting happens. The subjects are de-coupled from the observer in a similar way that events and event handlers work.
      
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16475192
oops. forgot... We need to set things in motion... Here is where we call the CountToTen method, notice that we get a message box because once it hits ten, the OnCountedToTen event is raised.

private void button_Click(object sender, System.EventArgs e)
{
    numberCounter.CountToTen();
}
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16475213
So if you wanted to use events then you could raise an event when a student is enrolled. Then another class can handle that event and do what it needs to do. Since this is homework I don't want to give away too much, but you could definitely use events in your situation (which really is pretty much the observer pattern).
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16477437
CORRECTION:

The line that reads:
the observer notifies all of the "subjects" when something interesting happens

should read:
the "subject" notifies all of the "observers" when something interesting happens.

Sorry about the confusion.
0
 

Author Comment

by:scarface7
ID: 16483554
Nice explanation !
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question