Link to home
Start Free TrialLog in
Avatar of riscy
riscy

asked on

Design Pattern, observer and observable, transulation from Java to C#

I was experimenting design pattern using Head First Design Pattern which is primary for java.
So far I managed to adopt the code into C# until on page 67

import java.util.Observable
import java.util.Oberver

I was looking for library based on above for the C# and found nothing relevent. It not clear if this actually exist for C#, I thing it don't.

Is there alternative method or solution that work for C#.

Thanks
Avatar of PoeticAudio
PoeticAudio

You can use delegates / events in C#, that's really close to how the observer pattern works.

The object that raises the event is like the subject, and all of the objects that are tied into the event handler are like observers.

Do you need a code example?
ASKER CERTIFIED SOLUTION
Avatar of PoeticAudio
PoeticAudio

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just so you know, you can pass any object back to the event handlers, for example, lets say you wanted to alter it a bit...


public class Subject
{
    public delegate void OnCountedEventHandler(int NumCountedTo);
    public event OnCountedEventHandler OnCounted;

    public Subject()
    {
    }

    public void CountToTen()
    {
        for(int i = 1; i <= 10; i++)
        {
            OnCounted(i);  //pass the number that the subject has counted to thus far.
        }
    }
}

There is other crap too, like when you see events in windows applications you often see an object called sender and another object that is a System.EventArgs. You can create your own EventArgs class and pass back info through that as well. That is beyond the scope of my point though.