Java implements generic delegates like c#action<t>

Source: Internet
Author: User
Tags try catch

first, C # action<t> generic delegate (help Understanding Delegates)

Describe:

Encapsulates a method that takes only one parameter and does not return a Value.

Grammar:

public delegate void Action<t> (T arg);

T:

Parameter type: the parameter type of the method encapsulated by this delegate

Arg

Parameters: parameters for methods encapsulated by this delegate

Note:

This delegate allows you to pass a method as a parameter. action<t> Generic Delegate: encapsulates a method that takes only one parameter and does not return a Value. You can use this delegate to pass a method as an argument without explicitly declaring a custom Delegate. The method must correspond to the method signature defined by this Delegate. In other words, the encapsulated method must have a parameter passed to it by value, and the value cannot be returned. of course, generic delegates do not only support only one parameter, it can support up to four Parameters.

Example:

When you use the action<t> delegate, you do not have to explicitly define a delegate that encapsulates a method that has only one parameter. The following code explicitly declares a delegate named DisplayMessage and assigns a reference to the WriteLine method or Showwindowsmessage method to its delegate instance.

Using system;using system.windows.forms;delegate void DisplayMessage (string message);p ublic class testcustomdelegate{ public static void Main () {displaymessage messagetarget; if (environment.getcommandlineargs (). Length > 1) messagetarget = showwindowsmessage;elsemessagetarget = Console.writeline;messagetarget ("Hello, World!"); } private static void Showwindowsmessage (string Message) {messagebox.show (message);}}

The following simplifies this code by instantiating a action<t> delegate instead of explicitly defining a new delegate and assigning a named method to the Delegate.

Using system;using system.windows.forms;public class testaction1{public static void Main () {action<string> messagetarget; If (environment.getcommandlineargs (). Length > 1) messagetarget = showwindowsmessage;elsemessagetarget = Console.writeline;messagetarget ("Hello, World!"); } private static void Showwindowsmessage (string Message) {messagebox.show (message);}}

The following uses the Action<t> delegate to print the contents of the list<t> Object. Use the Print method to display the contents of the list to the Console. The content is also displayed to the console using anonymous METHODS. Note that the example does not explicitly declare the action<t> variable. instead, it passes a reference to the method that takes a single argument and does not return the value to List<t>. A ForEach method whose single argument is a action<t> delegate. similarly, in the C # example, the,action<t> delegate is not explicitly instantiated because the signature of the anonymous method matches the List<t>. The signature of the Action<t> delegate expected by the ForEach Method.

Using system;using system.collections.generic;class program{static void Main () {list<string> names = new List< String> (); Names. ADD ("Bruce"); Names. ADD ("Alfred"); Names. ADD ("Tim"); Names. ADD ("Richard");//Display The contents of the list using the print Method.names.ForEach (print);//the following Demonstrat Es the anonymous method feature of c#//to display the contents of the list to the Console.names.ForEach (delegate (String n Ame) {console.writeline (name);});} private static void Print (string S) {console.writeline (s);}}

second, summary:

Definition: a delegate is a time to customize the execution of a method.

Points:

1. Define the METHOD.

2. Declare the Object.

3. Assign a value to the object (that is, the execution method).

third, the Java implementation of the delegation

Java is not possible to implement the delegation, because there is no such mechanism, Java to implement a similar function of the delegate can only use the Interface/inner class, casually see a awt/swing program on the CICADA.

1. Inner-class real- present entrustment

<span style= "color: #000000;" >public class  implementation delegate {public   static void main (string[] Args) {          //declaration object    Implementation Delegate test = new Implementation Delegate ();    Delegate T =test. New Delegate ();              Object assignment Execution Method       t.t ();   }      Define delegate   class delegate {public      void T () {         System.out.println ("test delegate");      }   }} </span>

2. Interface Implementation delegation

<span style= "color: #000000;" >public interface Delegate {public void T ();} The public class implements the delegate  implements delegate {public    static void main (string[] Args) {    implements the delegate test = new Implementation Delegate ();        Test. T ();    }        public void T () {       System.out.println ("test delegate");}    } </span>

four, application of generic delegate in Project

1. C # Generic delegate application in the project reference url:http://www.cnblogs.com/ASPNET2008/archive/2010/04/05 /1704405.html

2. C # project Instances

Question: I think when you do an exception, the try catch is used to catch the exception, and the log is done in the catch block, but each method writes a heap of try catches that are often somewhat awkward. Although it is recommended to try to catch a specific error exception when writing a program, there is always an unexpected exception thrown, which is a good practice to capture exception directly.

Scenario: when the client invokes the WCF service, we all need to do exception handling at the customer, the most common error exception for the communicationexception,timeoutexception,exception example is as Follows:

Try            {                //execute method call ...                (proxy as Icommunicationobject). Close ();            }            Catch (communicationexception Ex)            {                (proxy as icommunicationobject). Abort ();                WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data anomaly communicationexception:" + Ex. ToString ());            }            Catch (timeoutexception Ex)            {                (proxy as icommunicationobject). Abort ();                WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data timeout timeoutexception:" + Ex. ToString ());            }            Catch (Exception Ex)            {                      (proxy as icommunicationobject). Close ();                      WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data anomaly exception:" + Ex. ToString ());            }


But if this code spreads throughout the project, I think there is a need for refactoring, because it is best not to have replication-like code appearing in the project, so we can use the invoke form to refactor our existing code, given two methods, one with no return value, and one with a Value.

The code after using action<t> is as Follows:

public static void invoke<tcontract> (tcontract proxy, action<tcontract> Action) {try                {action (proxy); (proxy as Icommunicationobject).            Close (); } catch (communicationexception Ex) {(proxy as icommunicationobject).                Abort (); WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data anomaly communicationexception:" + Ex.            ToString ()); } catch (timeoutexception Ex) {(proxy as icommunicationobject).                Abort (); WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data timeout timeoutexception:" + Ex.            ToString ()); } catch (Exception Ex) {(proxy as icommunicationobject).                      Close (); WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data anomaly exception:" + Ex.            ToString ()); }} public static Treturn invoke<tcontract, treturn> (tcontract proxies, Func<tcontract, treturn> func) {treturn returnvalue = Default (treturn);            Try {returnvalue = func (proxy); } catch (communicationexception Ex) {(proxy as icommunicationobject).                Abort (); WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data anomaly communicationexception:" + Ex.            ToString ()); } catch (timeoutexception Ex) {(proxy as icommunicationobject).                Abort (); WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data timeout timeoutexception:" + Ex.            ToString ()); } catch (Exception Ex) {WebLog.SquareLog.CommonLogger.Error ("take Points Plaza Home Hotel Data Exception Exception: "+ Ex.            ToString ());        } return returnvalue; }


How to Invoke: It can be seen that the client code has become a concise code, which completes the complete exception handling, but also all can be caught in the exception information Record.

Calling Code:

List = errorhandler.invoke<isearchhotelforsquare, list

3. Summary

Self-understanding: The delegate is used when a lot of code is the same, part of the code is different and different code in the overall code in the same position, you can encapsulate the whole part into a method (method name, all), and then the different parts of the code into a method with no return value (method name such as: part), Then use action<t>, passing the part method like a parameter to the all Function. This implements the refactoring of the Code.

The above is implemented in C # with action<t>.

There is no action<t> in java, and generic delegates cannot be implemented, only by using interfaces and inner Classes.

Here is an example of the same functionality as the Java implementation and action<t>.

Examples are as Follows:

(1) Common methods

public class Allclass {publicly static void all (String S,common Common) {       //can write common code here       common.print (s);       The common code can be written here   }}


(2) interfaces to be implemented by different codes

public interface Common {public void print (String s);   }


(3) the first class to implement an interface

public class A implements common{public void print (String s) {System.out.print (s+= "a");} public static void main (string[] Args) {String s = "test";    Allclass.all (s,new A ());}}


(4) the second class for implementing an interface

public class A implements common{public void print (String s) {System.out.print (s+= "a");} public static void main (string[] Args) {String s = "test";    Allclass.all (s,new A ());}}


Java implements generic delegates like c#action<t>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.