I'm trying to put in practice the Observer Pattern, as seen in the provided code.
the Subject, Observer and DisplayElement are interface classes. CurrentConditionsDisplay class implements Observer and DisplayElement so it can get updated from the WeatherData class. as VBA doesn't support constructor with parameter, I created a sub in order to save a weatherData object and use it to register the CURRENT OBJECT. I pass the current object using Me.
when I run the main code (WeatherStation), the runtime error 438 comes up right when I pass Me as parameter (weatherData.registerObserver (Me)).
I'm appreciate any help.
Observer interface:
Option Compare Database
Option Explicit
Public Sub update(temperature As Double, humidity As Double, pressure As Double)
End Sub
Subject interface:
Option Compare Database
Option Explicit
Public Sub registerObserver(o As Observer)
End Sub
Public Sub removeObserver(o As Observer)
End Sub
Public Sub notifyObservers()
End Sub
DisplayElement interface:
Option Compare Database
Option Explicit
Public Sub display()
End Sub
WeatherData subclass:
Option Compare Database
Option Explicit
Implements Subject
Private m_observers As New Scripting.Dictionary
Private m_temperature As Double
Private m_humidity As Double
Private m_pressure As Double
Public Sub Subject_registerObserver(o As Observer)
m_observers.Add o, o
End Sub
Public Sub Subject_removeObserver(o As Observer)
If (m_observers.Exists(o)) Then
m_observers.Remove (o)
End If
End Sub
Public Sub Subject_notifyObservers()
Dim i As Long
Dim objeto As Observer
For i = 0 To m_observers.Count - 1
Set objeto = m_observers.Items(i)
objeto.update m_temperature, m_humidity, m_pressure
Next i
End Sub
Public Sub measurementsChanged()
Call Subject_notifyObservers
End Sub
Public Sub setMeasurements(temperature As Double, humidity As Double, pressure As Double)
m_temperature = temperature
m_humidity = humidity
m_pressure = pressure
Call measurementsChanged
End Sub
CurrentConditionsDisplay subclass:
Option Compare Database
Option Explicit
Implements Observer
Implements DisplayElement
Private m_temperature As Double
Private m_humidity As Double
Private m_weatherData As Subject
Public Sub CurrentConditionsDisplay(weatherData As Subject)
Set m_weatherData = weatherData
weatherData.registerObserver (Me)
End Sub
Public Sub Observer_update(temperature As Double, humidity As Double, pressure As Double)
m_temperature = temperature
m_humidity = humidity
Call DisplayElement_display
End Sub
Public Sub DisplayElement_display()
Debug.Print ("Current conditions: " + m_temperature + "F degrees and " + m_humidity + "% humidity")
End Sub
WeatherStation main code:
Option Compare Database
Option Explicit
Public Function WeatherStation()
Dim wData As New weatherData
Dim currentDisplay As New CurrentConditionsDisplay
Call currentDisplay.CurrentConditionsDisplay(wData)
Call wData.setMeasurements(80, 65, 30.4)
End Function