I'm doing a short presentation tomorrow evening at my local NxtGenUG user group meeting on the subject of the Observer Pattern.
I've been doing a lot of reading lately about Design Patterns. Design patterns are recognised solutions to common software development problems and there is a lot more awareness of them in the Microsoft developer community thanks to the efforts of the Microsoft Patterns and Practices team and events such as DDD.
The Observer pattern is one of the simpler design patterns to understand. In a nutshell, it is a mechanism which allows one or more objects (classes) in your program to be notified of changes in state within another object so that they can then update themselves, or take some other action based on the state of the observed object. It is one of my favourite design patterns, because when I discovered it, it was if I was a blind person who could suddenly see again.
You see, about two years ago, I was writing a case management system for the secured loans department within the company I was working for at the time. The application had an MDI-style interface where multiple child forms could be open within a single parent window, each child form displaying some subset of the applicant's details (employment status, outstanding credit, etc.). However, early in the project, I ran into problems trying to keep the information on all the child forms synchronized when the details or status of a case changed. I toyed with several solutions:
- only allowing one child form to be open at a time
- writing code in each child form's Activate event to get the latest data from the database
- putting a "refresh" button on each child form which, when clicked, would get the latest data from the database
None of these options seemed particularly satisfactory, but I didn't know any other way of solving the problem at the time. In the end, I went for the last option, as it seemed the "least bad" of the three.
Now, fast-forward two years: I was reading an article about the Observer pattern in a magazine and as I read, it slowly dawned on me that this was the solution I had been looking for! If only I had known about it sooner, it would have saved me so much time.