Delegates and Events as component technology for GoF Observer pattern ?


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.
scarface7Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PoeticAudioCommented:
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.
      

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PoeticAudioCommented:
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();
}
PoeticAudioCommented:
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).
PoeticAudioCommented:
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.
scarface7Author Commented:
Nice explanation !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.