Effective Java 21 Use function objects to represent strategies

Theory

In the Java the function pointers is implemented by the declaring an interface to represent strategy and a class that implements this interface for each concrete strategy. It is possible to define an object whose methods perform operations on other objects, passed explicitly to the methods. An instance of a class that exports exactly one such method is effectively a pointer to that method.

   

package com.effectivejava.classinterface;  

import java.util.Arrays;

import java.util.Comparator;

   

/**

* @author Kaibo

*

*/

public class StringLengthComparator implements Comparator<String> {  

public static final StringLengthComparator INSTANCE = new StringLengthComparator();

       private StringLengthComparator() {

}

/*

* override the super class key method.

*/

public int compare(String s1, String s2) {

return s1.length() - s2.length();

}

   

public static void main(String[] args) {

String[] a = new String[] { "I", "This", "a", "is" };

System.out.println("a origin values:");

printStringArray(a);

System.out.println("b sorted values:");

Arrays.sort(a, StringLengthComparator.INSTANCE);

for (int i = 0, len = a.length; i < len; i++)

System.out.println(a[i]);

System.out.println();

String[] b = new String[] { "He", "is", "a", "programmer" };

System.out.println("b origin values:");

printStringArray(b);

System.out.println("b sorted values:");

System.out.println();

// implement the compartor strategy by anounymous class

Arrays.sort(b, new Comparator<String>() {

public int compare(String s1, String s2) {

return s1.length() - s2.length();

}

});

}

private static void printStringArray(String[] strs) {

for (int i = 0, len = strs.length; i < len; i++)

System.out.println(strs[i]);

}

}

   

Note

  1. Please give a field a discriptive name for the specific implementation.
  2. The anonymous class may create a new instance for each invoking.
  3. When a concrete strategy is designed 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 instead of expose it to the public directly.

/**

*

*/

package com.effectivejava.classinterface;

import java.io.Serializable;

import java.util.Comparator;

/**

* @author Kaibo

*

*/

// Exporting a concrete strategy

class Host {

private static class StrLenCmp implements Comparator<String>, Serializable {

private static final long serialVersionUID = 1L;

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

}

   

作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/haokaibo/p/use-function-objects-to-represent-strategies.html