java : Function objects as strategies

标签 java oop interface function-pointers effective-java

我正在阅读 Effective Java。在讨论使用函数对象作为策略的部分中,存在以下段落。

Because the strategy interface serves as a type for all of its concrete strategy instances, a concrete strategy class needn’t be made public to export a concrete strategy. Instead, a “host class” can export a public static field (or static factory method) whose type is the strategy interface, and the concrete strategy class can be a private nested class of the host

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

我的问题是,使用上述方式有什么特别的优势吗?通过公开具体策略来导出策略有什么问题?

最佳答案

是的,有。这样你返回的是接口(interface)而不是具体类,所以如果你更改 Comparator 接口(interface)的具体实现,你不必也修改客户端类(我认为这是使用接口(interface)的最重要原因)。

例如:

//inside aClass

Comparator c = Host.STRING_LENGTH_COMPARATOR; //Programming against interfaces is different from:
StrLenCmp  c = Host.STRING_LENGTH_COMPARATOR; //programming against concrete class

假设将来您将使用另一个实现(我们称之为 NewStrLenCmp)更改 StrLenCmp,而不是如果您针对接口(interface) Comparator 进行编程则不必修改 aClass。

Comparator c = Host.STRING_LENGTH_COMPARATOR; //still work because interface doesn't changed
NewStrLenCmp  c = Host.STRING_LENGTH_COMPARATOR; // problem: you need to modify the client class in order to use the new concrete type: bad idea

关于java : Function objects as strategies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993275/

相关文章:

java - 将方法 makeEvent() 设为静态有什么优点吗?

c# - 在类及其成员之间共享变量

c++ - 将父项转换为子项

java - 了解接口(interface)当前类路径中是否有实现类

visual-studio - F12 - 转到接口(interface)的实现

java - 在 LinkedHashSet 的第 0 个位置插入元素的成本?

Java Applet 电子邮件问题

java - 从其他 Bean 填充一个 Bean

php - 如何在 Drupal 8 上更新自定义用户字段

oop - 糟糕的 OO 设计问题 - 我需要 Java 中的一些通用功能,但不知道如何实现它