Strategy
英文简单描述
Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm change dynamically.
How to
Strategy
declares an interface common to all supported algorithms.
ConcreteStrategy
implements the algorithm using the Strategy interface.
Context
is configured with a ConcreteStrategy object.
maintains a reference to a Strategy object.
may define an interface that lets Strategy access its data.
Known cases
Linebreak
Encrypt Algorithm
UML
代码实现:
委托和继承:
策略是通过另一个层次结构IStrategy来实现不同算法的,Context将compute委托给策略类
也可以用另一种方法来实现Context的compute的多样化:即继承Context,对于不同的compute提供不同的子类
这就涉及到委托和继承的选择问题
委托比继承灵活,可以动态配置,不会造成子类级数增长,另外可以通过对象的合成来实现多种功能(Decorator)
继承则相对不灵活,一旦选择了子类后,不能动态配置
另外,委托是黑盒重用,继承是白盒重用,应该多使用委托少用继承