[color=red]Purpose[/color]
Defines a set of encapsulated algorithms that can be swapped
to carry out a specific behavior.
[color=red]Use When[/color]
1 The only difference between many related classes is their
behavior.
2 Multiple versions or variations of an algorithm are required.
3 Algorithms access or utilize data that calling code shouldn’t
be exposed to.
4 The behavior of a class should be defined at runtime.
5 Conditional statements are complex and hard to maintain.
[color=red]Example[/color]
When importing data into a new system different validation
algorithms may be run based on the data set. By configuring the
import to utilize strategies the conditional logic to determine
what validation set to run can be removed and the import can be
decoupled from the actual validation code. This will allow us to
dynamically call one or more strategies during the import.
package javaPattern;
public interface Strategy {
public void execute();
}
class ConcreteStrategyA implements Strategy{
public void execute(){
System.out.println("算法A");
}
}
class ConcreteStrategyB implements Strategy{
public void execute(){
System.out.println("算法B");
}
}
class Context{
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void someMethod(){
strategy.execute();
}
public static void main(String[] args) {
ConcreteStrategyA csA = new ConcreteStrategyA();
Context context = new Context(csA);
context.someMethod();
}
}
Strategy模式與Template Method模式都是對不同算法的抽象與封裝,但它們的實現粒度不一樣。Strategy模式從類的角度,對整個算法加以封裝,Template Method模式從方法的角度,對算法的一部分加以封裝,且Template Method模式有一個方法模板的概念,在作爲抽象類的父類裏,定義了一個具有固定算法並可以細分爲多個步驟的模板方法(public)。