Implementing the Java Delegation Event Model

The code below defines an event (GooEvent), a class that raises the event (SampleGooEventSource) and a class that handles the event (SampleGooListener). Data is passed to the event handler in members of the GooEvent object that is passed to the Goo method defined in the GooListener interface. Handlers can be registered by passing them to the SampleGooEventSource’s AddGooListener method. When the event source raises the event, the Goo method of all listeners will be called.

Notice that this code is not best practice for .NET programming, it simply imitates the pattern used in Java for event handling for demonstration purposes:

Public Module Program
    Public Sub Main()
        Dim g As New SampleGooEventSource()
        Dim gl As New SampleGooListener()
        g.AddGooListener(gl)
        g.DoSomething()
        g.RemoveGooListener(gl)
        g.DoSomething()
    End Sub
End Module

Public Class EventObject
    Private m_Source As Object

    Public Sub New(ByVal Source As Object)
        m_Source = Source
    End Sub

    Public ReadOnly Property Source() As Object
        Get
            Return m_Source
        End Get
    End Property
End Class

Public Class SampleGooEventSource
    Private m_GooListeners As New ArrayList()

    Public Sub AddGooListener(ByVal Listener As GooListener)
        m_GooEventListeners.Add(Listener)
    End Sub

    Public Sub RemoveGooListener(ByVal Listener As GooListener)
        m_GooEventListeners.Remove(Listener)
    End Sub

    Private Sub RaiseGoo(ByVal e As GooEvent)
        Dim Listener As GooListener
        For Each Listener In m_GooListeners
            Listener.Goo(e)
        Next Listener
    End Sub

    Public Sub DoSomething()

        ' Raise the event.
        RaiseGoo(New GooEvent(Me, 22))
    End Sub
End Class

Public Class GooEvent
    Inherits EventObject

    Private m_Foo As Integer

    Public Sub New(ByVal Source As Object, ByVal Foo As Integer)
        MyBase.New(Source)
        Me.Foo = Foo
    End Sub

    Public Property Foo() As Integer
        Get
            Return m_Foo
        End Get
        Set(ByVal Value As Integer)
            m_Foo = Value
        End Set
    End Property
End Class

Public Interface GooListener
    Sub Goo(ByVal evt As GooEvent)
End Interface

Public Class SampleGooListener
    Implements GooListener

    Public Sub Goo(ByVal evt As GooEvent) Implements GooListener.Goo
        Console.WriteLine("Event raised.")
    End Sub
End Class