Observer Design Pattern for Windows Controls






1.24/5 (10 votes)
Feb 3, 2006
2 min read

39208

414
The puropse of this article to implement an Observer pattern for Windows controls, with the change in data of one MDI child, How to get the other registered forms to intimate the changes.
Introduction
I was working on a health care project, and in that project I found that information about same thing can e entered from multiple MDI child forms, but if any two such forms that can add same information are opened at the same time, then if the user adds some data ion control on one form it is not updated on the related control on the other opened form.
Thats why I found a simple but really useful solution. It implements two main design Patterns, 1) Singelton 2) Observer, both patterns helped me to accomplish my task, and I think it might be useful for you people as well.
Problem Statement
Now, in the demo application I have datagrid controls on three form. Now I want if the data is added or deleted from a grid on one form it should be deleted from the other two grids as well (if the forms are created).
Solution
I came up with a simple solution, what I did was, I made a new MDI Application. Then I made three Child forms, each containing a datagrid and a Toolbar to add/delete rows. All the three child forms have been Inherited from FrmParent, that in turns has been inherited from windows.Forms.Form, FrmParent has a Public Overridable method "Update", that is called by the Ovserver class to update the changes.
Observer class is a combination os singleton and Observer design patterns. It has four methods:
1) Public Shared Function Instance() As Observer
This is a shared method, and returns the singleton object of the class.
2) Public Sub Add(ByVal form As FrmParent)
This method add the form tho the ArrayList.
3) Public Sub Notify(ByVal row As DataRow, ByVal op As FrmParent.Operation)
This method intimates the registered forms to get the updates.
4) Public Sub Release(ByVal form As FrmParent)
On form close this method is called to release the form from the ArrayList of Observer class.
Note: Open all the three forms in the application,and then start data entry, otherwise the newly adds will take effect but the previous data will not come on the new form.