Asdfasf

Saturday, August 23, 2014

EJ-21 Use Function Objects to Represent Strategies

Ref: Effective Java by Joshua Bloch

Strategy classes are often declered using anonymous classes and pessed to target operation. The following statement sorts an array of strings according to length:

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

// 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: