Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Delegate? [closed]

Tags:

oop

delegates

People also ask

What is the difference between delegate and closure?

If you look at some delegate methods (and nearly all dataSource methods), there is an expected return value. That means the delegating object is asking for the state of something. While a closure could reasonably maintain state or at least deduce state, this is really an object's role. Think about it.

Why use delegates?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

What is the difference delegates and callbacks?

Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.

What is a delegate groovy?

The delegate of a closure is an object that is used to resolve references that cannot be resolved within the body of the closure itself. If your example was written like this instead: def say = { def m = 'hello' println m } say.delegate = [m:2] say() It prints 'hello', because m can be resolved within the closure.


I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.

The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.

Here's a reference for C# you can look at:

In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:

public static double CalcTotalMethod1(double amt)
{
    return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
    return amt * .056 + 42.43;
}

We could declare a delegate signature like this:

public delegate double calcTotalDelegate(double amt);

And then we could declare a method which takes the delegate as a parameter like this:

public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
    return calcTotal(amt);
}

And we could call the CalcMyTotal method passing in the delegate method we wanted to use.

double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);

a delegate is simply a function pointer.
simply put you assign the method you wish to run your delegate. then later in code you can call that method via Invoke.

some code to demonstrate (wrote this from memory so syntax may be off)

delegate void delMyDelegate(object o);

private void MethodToExecute1(object o)
{
    // do something with object
}

private void MethodToExecute2(object o)
{
    // do something else with object
}

private void DoSomethingToList(delMyDelegate methodToRun)
{
    foreach(object o in myList)
        methodToRun.Invoke(o);
}

public void ApplyMethodsToList()
{
    DoSomethingToList(MethodToExecute1);
    DoSomethingToList(MethodToExecute2);
}

Taken from here

Q What are delegates?
A When an object receives a request, the object can either handle the request itself or pass the request on to a second object to do the work. If the object decides to pass the request on, you say that the object has forwarded responsibility for handling the request to the second object.

Or, as an easy pseudo example: something sends a request to object1. object1 then forwards the request and itself to object2 -- the delegate. object2 processes the request and does some work. (note: link above gives good examples)


Think about delegate as about a simplified implementation of Command pattern.


A delegate is an object that can refer to a method. Thus, when we create a delegate, we are creating an object that can hold a reference to a method. Furthermore, the method can be called through this reference. Thus, a delegate can invoke the method to which it refers. The principal advantage of a delegate is that it allows us to specify a call to a method, but the method actually invoked is determined at runtime, not at compile time.

Simple Delegate

Declaration of delegate:
delegate-modifier delegate return-type delegate-name(parameters)
Implementation of delegate:
Delegate-name delegate-object=new Delegate-name(method of class)

http://knowpacific.wordpress.com/2012/01/26/delegate/


Here I am going to explain delegates, multicast delegates and their usage.. Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. We can say a delegate is a type that defines a method signature.

When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. Advantages of using delegates are, Encapsulating the method's call from caller Effective use of delegate improves the performance of application Used to call a method asynchronously. There are some properties of delegates are

Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.

public delegate type_of_delegate delegate_name() // Declaration

You can use delegates without parameters or with parameter list
If you are referring to the method with some data type then the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer. Here I am giving an example with String.

The following example shows a delegate operation:

    namespace MyDelegate
    {
        class Program
        {
            private delegate void Show(string s);


            // Create a method for a delegate.
            public static void MyDelegateMethod(string me

ssage)
        {
            System.Console.WriteLine(message);
        }

        static void Main(string[] args)
        {
            Show p = MyDelegateMethod;
            p("My Delegate");
            p.Invoke("My Delegate");
            System.Console.ReadLine();
        }
    }
}

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.

 delegate void MyMulticastDelegate(int i, string s);
 Class Class2
 {
  static void MyFirstDelegateMethod(int i, string s)
  {
    Console.WriteLine("My First Method");
  }

  static void MySecondDelegateMethod(int i, string s)
  {
    Console.WriteLine("My Second Method");
  }

  static void Main(string[] args)
  {
    MyMulticastDelegate Method= new MyMulticastDelegate(MyFirstDelegateMethod);
    Method+= new MyMulticastDelegate (MySecondDelegateMethod);
    Method(1,"Hi");             // Calling 2 Methodscalled
    Method-= new MyMulticastDelegate (MyFirstDelegateMethod);
    Method(2,"Hi");             //Only 2nd Method calling
  }
}

Here Delegate is added using the += operator and removed using the -= operator.

Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed—they cannot be derived. Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback.


A great explanation and practical implementation of the Delegate pattern can be found in the Google Collections Forwarding Classes (also, the Decorator pattern).