Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / Visual Basic
Article

Using an Observer design pattern to keep multiple forms up to date

Rate me:
Please Sign up or sign in to vote.
2.58/5 (8 votes)
29 May 20051 min read 54.5K   127   29   9
This article demonstrates how multiple forms can be updated simultaneously using Singleton and Observer Design Patterns.

Introduction

This article describes how to keep multiple instances of objects up to date using Singleton and Observer Design Patterns.

Singleton Design Pattern

We want to be able to share a variable between different objects. The first step to doing this is to ensure that we store the variable only once. To do this we use a Singleton class, this is a class that can only be instantiated once.

The code below is a VB.NET translation of a C# version of a Singleton that can be downloaded from www.dofactory.com.

VB
Public Class ColorObserver

#Region "Singleton Design Pattern"
    REM Use a Singleton Design pattern to ensure _
            that this class can only be instantiated once
    Public Shared s As ColorObserver
    Public Shared flag As Boolean

    Private Sub New()
        'private constructor disallowing other to create object directly
    End Sub
    Public Shared Function getSingletonObject() As ColorObserver
        If flag = False Then
            'First instance
            'return a new object
            s = New ColorObserver
            flag = True
            Return s
        Else
            'future object request 
            'return an already created object
            Return s
        End If
    End Function
#End Region
End Class

Observer Design Pattern

The next step is to be notified when a change occurs. This can be done using an Observer design pattern. There are many ways of implementing an Observer pattern. An Observer implemented with inheritance can be downloaded from here. I have chosen different approaches by using Delegates and Events as described in MSDN. The idea is to raise an event when data changes. Objects subscribe to the observer by listening for the ColorUpdated event.

VB
Public Class ColorObserver

    Public Shared Event ColorUpdated()
    Private Shared _SelectedColor As Colors
    Public Enum Colors
        Red = 0
        White = 1
        Blue = 2
    End Enum

#Region "Singleton Design Patern"
 ..
#End Region

#Region "Color Functions"
    Public Property Color() As Colors
        Get
            Return _SelectedColor
        End Get
        Set(ByVal Color As Colors)
            _SelectedColor = Color
            RaiseEvent ColorUpdated()
        End Set
    End Property
#End Region

End Class

To subscribe to this observer, you need:

VB
Private iColorObserver As ColorObserver

Private Sub frmChild_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
    iColorObserver = iColorObserver.getSingletonObject
    AddHandler iColorObserver.ColorUpdated, AddressOf ChangeColor
End Sub

Private Sub ChangeColor()
    Select Case iColorObserver.Color
        Case ColorObserver.Colors.Red
            Me.BackColor = Color.Red
        Case ColorObserver.Colors.White
            Me.BackColor = Color.White
        Case ColorObserver.Colors.Blue
            Me.BackColor = Color.Blue
    End Select
End Sub

To update the color of all objects subscribing to the Observer:

VB
iColorObserver.Color = ColorObserver.Colors.Red

Conclusion

This is a good way of propagating updates across multiple windows. I hope you enjoyed the example.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Switzerland Switzerland
I am a Software Engineer currently working in a Re Insurance company.

Comments and Discussions

 
GeneralThread Safety Pin
Nigel-Findlater31-May-05 19:47
Nigel-Findlater31-May-05 19:47 
Here's another input from a friend that is interesting:

The getSingletonObject is not thread-safe. Again, a singleton-related issue. This could be offset by initializing in the shared constructor.

If you want multiple forms to "observe" the same color state, then a better design than using a singleton would be to create a ColorObserver instance in your Main and pass that same instance to all forms you create. This way, you don't need singleton and the problems it entails like thread-safety, you get rid of the memory leak and get a very lean and mean design. It's does one thing and does it well.

have fun...

Nigel...
GeneralHere are some simplifications Pin
Nigel-Findlater31-May-05 19:30
Nigel-Findlater31-May-05 19:30 
GeneralRe: Here are some simplifications Pin
fiwi463pfa30-Oct-07 0:09
fiwi463pfa30-Oct-07 0:09 
GeneralMemory leak Pin
wout de zeeuw30-May-05 0:18
wout de zeeuw30-May-05 0:18 
GeneralRe: Memory leak Pin
Trance Junkie30-May-05 1:16
Trance Junkie30-May-05 1:16 
GeneralRe: Memory leak Pin
wout de zeeuw30-May-05 8:32
wout de zeeuw30-May-05 8:32 
GeneralRe: Memory leak Pin
ddarko10016-Oct-09 5:17
ddarko10016-Oct-09 5:17 
GeneralRe: Memory leak Pin
Nigel-Findlater31-May-05 19:49
Nigel-Findlater31-May-05 19:49 
GeneralRe: Memory leak Pin
wout de zeeuw31-May-05 22:35
wout de zeeuw31-May-05 22:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.