0

I have one class named DataClass. This Class is responsible to saving information in database, and In this class there are some methods for saving and reading from database, Except this class I have other classes called HTMLEditor, QueryBuilder , EmailSending, InforDetails. I need to listen to other classes by my data class , any time their information are changed then my Dataclass would be notified to save these information. I know there is one design pattern is called observer design pattern , with this design pattern, other classes(observers) are listening to one class(subject),any time the status of subject is changed then other observers are notified.

What should I do for this problem? Is there any design pattern for this situation?

horgh
  • 17,918
  • 22
  • 68
  • 123
Houshang.Karami
  • 179
  • 2
  • 14

2 Answers2

2

I think the interface you seek if INotifyPropertyChanged.

Microsoft Documentation: INotifyPropertyChanged

The implementation is very simple.

In every property set you do:

public bool MyProperty
{
    get { return myField; }

    set
    {
        if (myField != value)
        {
            myField= value;
            NotifyPropertyChanged();
        }
    }
}

And the method and events:

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Every observer only need to register to that event and they get a feedback when a property changed and which one did.

As extra, some control like PropertyGrid automatically register themselves when you feed them an object that implement that interface.

LightStriker
  • 19,738
  • 3
  • 23
  • 27
1

The INotifyPropertyChanged interface could be what you're after:

See here: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

You basically subscribe to an event within your other classes and those classes raise the event when a property changes.

Also, this SO question has an answer that is quite cool: Automatically INotifyPropertyChanged

Community
  • 1
  • 1
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138