java - Collections.sort 使用什么设计模式?

标签 java oop design-patterns collections polymorphism

当以下列方式将比较器应用于列表时,使用的是什么设计模式或这里使用的技术是什么?

Collections.sort(myCollection, new Comparator<MyItem>() {

    @Override
    public int compare(MyItem item1, MyItem item2) {
        return item1.getId().compareTo(item2.getId());
    }

});

最佳答案

长话短说:

Collections.sort 是简单多态替换的示例,无论您是使用函数式编程 还是面向对象编程 来进行此替换.术语策略模式 不能与多态性函数式编程 互换。

仍然可以说我们正在将排序 Strategy 传递给 sort 方法,但是没有 Context,它不是策略模式


When applying a comparator to a list in the following manner, what is the design pattern being used or what is the technique being used here?

由于此问题已被标记为OOP,因此此处本身没有使用OOP 设计模式。这就是普通的多态性在起作用。有些程序员可能将其称为策略模式,但我不同意。 Strategy 模式提倡组合而不是继承,其中您使用has-a 关系而不是is -a 关系。

一些程序员可能会进一步争辩说我们正在将排序 Strategy 传递给 Collections.sort 方法,所以这就是 Strategy Pattern;但是,需要承认的是,StrategyStrategy Pattern 的组件之一。 Strategy 模式的另一个重要组成部分是它的Context,它与Strategy 建立HAS-A 关系。此组件是策略模式背后的动机的核心,该模式更喜欢组合而不是继承。你不能从整体中取出一部分,但仍将分离的部分称为整体。您不能将 ContextStrategy Pattern 中取出,而仍然将其余部分称为 Strategy Pattern

Collections.sort 是一个static 方法,允许您多态替换Comparator 实现在运行时使用。


辅助 Material

让我们看看GoFStrategy Pattern的定义:

Encapsulating an algorithm in an object is the intent of the Strategy ( 315) pattern. The key participants in the pattern are Strategy objects (which encapsulate different algorithms) and the context in which they operate. Compositors are strategies; they encapsulate different formatting algorithms. A composition is the context for a compositor strategy.

....

Object composition offers a potentially more workable and flexible extension mechanism..

现在应该清楚,多态性策略模式 之间存在细微差别。 Strategy 模式讨论了一个使用组合上下文,如上面的粗体 中突出显示的那样。 Collections 类不与Comparator 建立组合 关系。此外,class diagram Strategy Pattern 显示了一个称为 Context 的组件,它构成了 Strategy 接口(interface)。

这个问题被标记为OOP,但如果我们想讨论Collections.sort 在函数式编程范式方面代表什么模式,我会说代表函数式编程。 (如果我必须将函数传递给方法等同于 OOP 模式,我会说它更像(不完全)命令模式而不是策略模式)

相关内容:Does Functional Programming Replace GoF Design Patterns?

关于java - Collections.sort 使用什么设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42442013/

相关文章:

java - 我如何找到循环中的第n项? java

javascript - 为什么在 OO JavaScript 中使用 "this"?

java - 当您想将一些通用功能应用于某些特定方法时使用的设计模式?

c++ - 通过 C++ 中的组合实现多态行为,无需多级继承

c# - 格式化文件的好方法

java - 错误 :android-apt plugin is incompatible with the Android Gradle plugin. 请改用 'annotationProcessor' 配置

java - 如何让 XML 解析器知道所有字符实体引用?

asp.net - 根据 bool 结果进行函数链接

java - A*算法Java

php - 为 Laravel 应用程序中的所有表单设置全局选项