Advantages of using delegates?

前端 未结 14 1358
渐次进展
渐次进展 2020-12-13 11:39

I\'m looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I\'ve heard that delegates can be used for this, but can\'t figure ou

14条回答
  •  感动是毒
    2020-12-13 12:13

    I'm repeating an answer I gave to this question.

    I've always like the Radio Station metaphor.

    When a radio station wants to broadcast something, it just sends it out. It doesn't need to know if there is actually anybody out there listening. Your radio is able to register itself with the radio station (by tuning in with the dial), and all radio station broadcasts (events in our little metaphor) are received by the radio who translates them into sound.

    Without this registration (or event) mechanism. The radio station would have to contact each and every radio in turn and ask if it wanted the broadcast, if your radio said yes, then send the signal to it directly.

    Your code may follow a very similar paradigm, where one class performs an action, but that class may not know, or may not want to know who will care about, or act on that action taking place. So it provides a way for any object to register or unregister itself for notification that the action has taken place.

提交回复
热议问题