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.
Public Class ColorObserver
#Region "Singleton Design Pattern"
that this class can only be instantiated once
Public Shared s As ColorObserver
Public Shared flag As Boolean
Private Sub New()
End Sub
Public Shared Function getSingletonObject() As ColorObserver
If flag = False Then
s = New ColorObserver
flag = True
Return s
Else
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.
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:
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:
iColorObserver.Color = ColorObserver.Colors.Red
Conclusion
This is a good way of propagating updates across multiple windows. I hope you enjoyed the example.