我正在尝试实践观察者模式,如提供的代码所示。
主题,观察者和 DisplayElement 是接口类。 CurrentConditionsDisplay 类实现了 Observer 和 DisplayElement ,因此可以从 WeatherData 类进行更新。由于VBA不支持带参数的构造函数,因此我创建了一个子程序来保存weatherData对象,并使用它来注册 CURRENT OBJECT 。我使用 Me 传递当前对象。
当我运行主代码( WeatherStation )时,当我通过 Me 作为参数( weatherData.registerObserver(Me))时,就会出现运行时错误438 )。
非常感谢您的帮助。
观察者界面:
Option Compare Database
Option Explicit
Public Sub update(temperature As Double, humidity As Double, pressure As Double)
End Sub
主题界面:
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界面:
Option Compare Database
Option Explicit
Public Sub display()
End Sub
WeatherData子类:
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子类:
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主要代码:
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