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 );}}