Strategy classes are often declered using anonymous classes and pessed to target operation. The following statement sorts an array of strings according to length:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Arrays.sort(stringArray, new Comparator<String>() { | |
public int compare(String s1, String s2) { | |
return s1.length() - s2.length(); | |
} | |
}); |
But note that using an anonymous class in this way will create a new instance each time the call is executed. When it is expected for repeated use, it is generally implemented as a private static member class and exported in a public static final field whose type is the strategy interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Exporting a concrete strategy | |
class Host { | |
private static class StrLenCmp | |
implements Comparator<String>, Serializable { | |
public int compare(String s1, String s2) { | |
return s1.length() - s2.length(); | |
} | |
} | |
// Returned comparator is serializable | |
public static final Comparator<String> | |
STRING_LENGTH_COMPARATOR = new StrLenCmp(); | |
... // Bulk of class omitted | |
} |
No comments:
Post a Comment