Monday, March 25, 2013

Observer Pattern

Did you know Real Studio includes several "design pattern" example projects, including: Decorator, Factory, Interpreter, LazyInitialization and Singleton?

Recently, someone on the mailing list asked how to do the Observer pattern using Real Studio. Here is a quick example to demonstrate it.

What is the Observer pattern?

You use the observer pattern when you have an object that needs to notify one or more other objects of specific changes. This is the definition from wikipedia:


"The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods."

For this example, I have a window with three radio buttons to set a color (Red, Green, Blue). When a radio button is clicked, the "observer" windows are notified of the change and change their background color to match what was clicked.

You can download the project from here:


Implementation Details
This design pattern is implemented using two interfaces: SubjectInterface and ObserverInterface.

The MainWindow implements SubjectInterface. It is responsible for tracking all the objects that want to observer (get notified of ) the change in color. This is done using an array of ObserverInterface objects.

The ObserverWindow implements ObserverInterface. This has one method (Notify) to implement which changes the background color of the window to the selected color.

When you click the "Add Observer" button, a new ObserverWindow is created and added to the array of observer objects.

When the color is changed by clicking a RadioButton, the code loops through all the observer objects in the array and call their Notify method.

The Remove All Observers button removes the open windows from the observer objects array. They will no longer get notified when the color changes.

This example project will also be included with Real Studio starting with 2013r1.

2 comments:

Mathias said...

Best book of design patters: Head First: Design Paterns, without that, you can hardly be called a software developer.

happyuk said...

Please see this link for a very simple implementation of the Observer pattern:

http://www.technical-recipes.com/2011/avoiding-circular-dependencies-using-observer-patterns/