Advantages of using delegates?

2019-01-21 21:06发布

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 out why they would be preferred over plain old interfaces implemented on observers. So,

  • Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?
  • Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?

14条回答
闹够了就滚
2楼-- · 2019-01-21 21:23

I've heard some "events evangelists" talk about this and they say that as more decoupled events are, the better it is.

Preferably, the event source should never know about the event listeners and the event listener should never care about who originated the event. This is not how things are today because in the event listener you normally receive the source object of the event.

With this said, delegates are the perfect tool for this job. They allow decoupling between event source and event observer because the event source doesn't need to keep a list of all observer objects. It only keeps a list of "function pointers" (delegates) of the observers. Because of this, I think this is a great advantage over Interfaces.

查看更多
▲ chillily
3楼-- · 2019-01-21 21:23

Here is something that i can write down as a reason of using delegate. The following code is written in C# And please follow the comments.

public delegate string TestDelegate();
protected void Page_Load(object sender, EventArgs e)
{
    TestDelegate TD1 = new TestDelegate(DiaplayMethodD1);
    TestDelegate TD2 = new TestDelegate(DiaplayMethodD2);
    TD2 = TD1 + TD2; // Make TD2 as multi-cast delegate
    lblDisplay.Text =  TD1(); // invoke delegate
    lblAnotherDisplay.Text = TD2();


    // Note: Using a delegate allows the programmer to encapsulate a reference 
    //       to a method inside a delegate object. Its like the function pointer
    //       in C or C++.    
}
//the Signature has to be same.
public string DiaplayMethodD1()
{
    //lblDisplay.Text = "Multi-Cast Delegate on EXECUTION"; // Enable on multi-cast 
    return "This is returned from the first method of delegate explanation";
}
// The Method can be static also
public static string DiaplayMethodD2()
{
    return " Extra words from second method";
}

Best Regards, Pritom Nandy, Bangladesh

查看更多
甜甜的少女心
4楼-- · 2019-01-21 21:25

You're an O/S, and I'm an application. I want to tell you to call one of my methods when you detect something happening. To do that, I pass you a delegate to the method of mine which I want you to call. I don't call that method of mine myself, because I want you to call it when you detect the something. You don't call my method directly because you don't know (at your compile-time) that the method exists (I wasn't even written when you were built); instead, you call whichever method is specified by the delegate which you receive at run-time.

查看更多
成全新的幸福
5楼-- · 2019-01-21 21:25

Well technically, you don't have to use delegates (except when using event handlers, then it's required). You can get by without them. Really, they are just another tool in the tool box.

The first thing that comes to mind about using them is Inversion Of Control. Any time you want to control how a function behaves from outside of it, the easiest way to do it is to place a delegate as a parameter, and have it execute the delegate.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-21 21:26

Actually there was an interesting back-and-forth between Sun and Microsoft about delegates. While Sun made a fairly strong stance against delegates, I feel that Microsoft made an even stronger point for using delegates. Here are the posts:

http://java.sun.com/docs/white/delegates.html

http://msdn.microsoft.com/en-us/vjsharp/bb188664.aspx

I think you'll find these interesting reading...

查看更多
三岁会撩人
7楼-- · 2019-01-21 21:27

Here is an example that might help.

There is an application that uses a large set of data. A feature is needed that allows the data to be filtered. 6 different filters can be specified.

The immediate thought is to create 6 different methods that each return the data filtered. For example

public Data FilterByAge(int age)

public Data FilterBySize(int size)

.... and so on.

This is fine but is a very limited and produces rubbish code because it's closed for expansion.

A better way is to have a single Filter method and to pass information on how the data should be filtered. This is where a delegate can be used. The delegate is a function that can be applied to the data in order to filter it.

public Data Filter(Action filter)

then the code to use this becomes

Filter(data => data.age > 30);

Filter(data => data.size = 19);

The code data => blah blah becomes a delegate. The code becomes much more flexible and remains open.

查看更多
登录 后发表回答