VB.NET 实现的观察者模式

Public Delegate Sub NotifyEventHandler(ByVal sender As Object)
Public Class PLC

    Public NotifyEvent As NotifyEventHandler

    Public Symbol As String = ""
    Public Info As String = ""

    Public Sub New(Symbol As String, info As String)
        Me.Symbol = Symbol
        Me.Info = info
    End Sub

    Public Sub AddObserver(ob As NotifyEventHandler)
        NotifyEvent = [Delegate].Combine(ob, NotifyEvent)

    End Sub
    Public Sub RemoveObserver(ob As NotifyEventHandler)
        NotifyEvent = [Delegate].RemoveAll(NotifyEvent, ob)
    End Sub

    Public Sub Update()
        ThreadPool.QueueUserWorkItem(New WaitCallback(Sub()
                                                          NotifyEvent(Me)
                                                      End Sub))

    End Sub
End Class

Public Class PLCStatus
    Inherits PLC

    Public Sub New(symbol As String, info As String)
        MyBase.New(symbol, info)
    End Sub

End Class

' 具体订阅者类

Public Class Subscriber
    Public Name As String = ""

    Public Sub New(name As String)
        Me.Name = name
    End Sub

    Public Sub ReceiveAndPrint(obj As Object)
        Dim plc As PLC = TryCast(obj, PLC)
         
        If Not plc Is Nothing Then
            Console.WriteLine("Notified {0} of {1}'s" + " Info is: {2}", Name, plc.Symbol, plc.Info)
        End If

    End Sub
End Class
 

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim plc As PLCStatus = New PLCStatus("TenXun Game", "Have a new game published ....")
        Dim lh As Subscriber = New Subscriber("李")
        Dim tom As Subscriber = New Subscriber("王")

        '// 添加订阅者

        plc.AddObserver(New NotifyEventHandler(AddressOf lh.ReceiveAndPrint))
        plc.AddObserver(New NotifyEventHandler(AddressOf tom.ReceiveAndPrint))

        plc.Update()

        Console.WriteLine("-----------------------------------")
        Console.WriteLine("移除王订阅者")
        plc.RemoveObserver(New NotifyEventHandler(AddressOf tom.ReceiveAndPrint))
        plc.Update()
        Console.ReadLine()
    End Sub
End Class

  

posted @ 2015-08-06 14:53  红耳  阅读(163)  评论(0编辑  收藏  举报