Learning notes for objective Java version 2: using function objects to express policies

Source: Internet
Author: User

Article 3: representation of a policy using a function object

 

Function pointers are mainly used to implement the policy mode. To implement the seed mode in Java, you must declare an interface to represent this policy and declare a class that implements this interface for each specific policy. When a specific policy is used only once, an anonymous internal class is usually used to declare and instantiate this specific policy class. When a specific policy is designed for reuse, its class is usually implemented as a private static member and exported through a common static final domain, its type is this policy interface.

Example 1:

Arrays. sort (StringArray, new Comparator <String> () {public int compare (String s1, String s2) {return s1.length ()-s2.length ();}});

Example 2:

Public class Host {private static class StrLenCmp implements Comparator <String>, Serializable {@ Overridepublic int compare (String s1, String s2) {return s1.length ()-s2.length ();}} public static final Comparator <String> STRING_LENGTH_COMPARATOR = new StrLenCmp (); public static void main (String [] args) {String s1 = ""; String s2 = ""; int result = Host. STRING_LENGTH_COMPARATOR.compare (s1, s2); System. out. println (result );}}

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.