Shared Delegates

One disadvantage of using delegates is that the calling code must instantiate the delegates it needs before it can use the delegate.
Rather than forcing the code to know which methods to use it would be better to get the delegate from the actual object classes themselves.
You can give each object class the responsibility for instantiating the delegate by implementing its own shared delegate.
The problem with shared delegates is that they must always be instantiated regardless of whether they are used or not.


You must first declare a Delegate with an identical signature.

Public Delegate Function Del_AskQuestion(ByVal sMessage As String) As Boolean 

Sub Main()
   Dim delAskQuestion As Del_AskQuestion

   delAskQuestion = New Del_AskQuestion(AddressOf MessageType.AskYesNo)

   If delAskQuestion.Invoke("Do you want to save this file ?") = True Then

   End If
End Sub

This class contains a shared function that returns True if the user answers Yes to the question.

Public Class MessageType 

   Public Shared Function AskYesNo(ByVal sMessage As String) As Boolean
      Dim answer As objMsgBoxResult

      objanswer = MsgBox(sMessage, MsgBoxStyle.YesNo Or MsgBoxStyle.Question)

      AskYesNo = (objanswer = MsgBoxResult.Yes)
   End Function
End Class


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext