Search code examples
c#data-bindinguser-interfaceobserver-pattern

Observer pattern Or DataBinding


My question is, would you implement the Observer pattern, or use databinding to do the following:

At the moment, i'm initializing a list of GuiDataObj. When an event is triggered, I look up the GuiDataObjById and then modify the object, which is databound to a GuiElement; which updates the GUI.

There are several GuiElements (at the moment are all of the same type, but this could change in the future), I want to be able to modify a class object, and have the GuiElement to auto-magically update the GuiElement with the reflected change.

public class GuiElement : ObservableImpl
{
    private string guiElementName;
    public String GuiElementName
    {
        get { return guiElementName; }
        set
        {
            guiElementName = value;
            NotifyObservers(guiElementName);
        }
    }

    private string status;
    public String Status
    {
        get { return status; }
        set
        {
            status = value;
            NotifyObservers(status);
        }
    }
}

public interface IObserver
{
    void Notify<T>(T watchObj);
}

public interface IObservable
{
    void Register(IObserver observer);
    void UnRegister(IObserver observer);
}

public class ObservableImpl : IObservable
{

    protected Hashtable _observerContainer = new Hashtable();

    public void Register(IObserver anObserver)
    {
        _observerContainer.Add(anObserver, anObserver);
    }

    public void UnRegister(IObserver anObserver)
    {
        _observerContainer.Remove(anObserver);
    }

    public void NotifyObservers<T>(T anObject)
    {
        foreach (IObserver anObserver in _observerContainer.Keys)
            anObserver.Notify(anObject);
    }
}

And then have my GuiElement update the Gui when notified of a change?

public partial class GuiElementControl : UserControl, IObserver
{

    public GuiElementControl()
    {
        InitializeComponent();
    }

    #region Implementation of IObserver

    public void Notify<T>(T watchObj)
    {
        if (watchObj is GuiElement)
        {
            UpdateGui(watchObj);
        }
    }

    private static void UpdateGui(object obj)
    {
        GuiElement element = obj as GuiElement;
        if (element != null)
        {
            NameLbl.Text = element.GuiElementName;
            StatusLbl.Text = element.Status;
        }
    }

    #endregion

would it be a more flexible design if I implemented data binding, instead of notifying an observer of changes? I guess what I'm really asking is, what's the most flexible way of visually representing a business object, that constantly has updates in real-time.

alt text http://devpupil.net/GuiConcept.PNG


Solution

  • I'd use an Observer. GUIs that auto-update their values when the underlying model/data they represent changes is one of the classic examples of using the Observer pattern.