策略设计模式如何表示对象之间的组合

How strategy design pattern represents combination between objects

我们知道策略设计模式属于行为设计模式,根据它们代表某种对象关系的事实进行分类。 任何人都可以在策略中解释如何维护对象关系以及在谁之间。我们创建一个包含不同实现的上下文,客户端将在运行时选择其中一个,并且也可以在另一个场景中更改。 但是这里是如何维护对象关系的,那两个对象是什么。

策略模式简单地表示使用对象的算法。这里的关系是调用策略的对象和表示策略的对象之间的关系。

interface FooSorter {
  List<Foo> sort(List<Foo> input);
}

class FooMergeSorter implements FooSorter { /* ... */ }
class FooHeapSorter implements FooSorter { /* ... */ }

/** The only thing you need to know about this class is that it needs Foo sorted. */
class YourContainerClass {
  FooSorter sortStrategy = new FooHeapSorter();

  void doSomething(List<Foo> listOfFoos) {
    // Sort according to the strategy.
    List<Foo> sortedList = sortStrategy.sort(listOfFoos);
    // ...
  }
}

从这个意义上说,容器class(上文,YourContainerClass)有责任select策略允许分配一个。它们使用的所有其他属性——实例控制,或者它们是如何提供的(通过你的上下文),或者它们是如何在调用的 class 上分配的——都超出了模式的范围。

请参阅 this answer 了解有关策略模式及其如何融入其他设计模式的更多信息。