1.定義
策略模式:定義了算法家族,分別封裝起來,讓它們之間可以互相替換,此模式讓算法的變化,不會影響到使用算法的用戶。
同樣以計算器的例子來展示策略模式。
2.UML:
3.Code
Operation.class:
abstract class Operation{
public double numberA;
public double numberB;
abstract double getResult();
}
子類:
OperationAdd.class:
class OperationAdd extends Operation{
public double getResult{
return numerA + numberB;
}
}
OperationSub.class:
class OperationSub extends Operation{
public double getResult{
return numerA - numberB;
}
}
OperationMul.class:
class OperationMul extends Operation{
public double getResult{
return numerA * numberB;
}
}
OperationDiv.class:
class OperationDiv extends Operation{
public double getResult{
if(numberB == 0){
throw new Exception("除數不能爲0");
}
return numerA / numberB;
}
}
Context.class:
class Context{
private Operation operation;
public Context(Operation opera){
operation = opera;
}
public double getResult(){
return operation.getResult();
}
}
Client.class:
public class Client{
public static void main(String[] args){
String operator = "+";
Operation operation = null;
switch(operator){
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
}
operation.numberA = 2;
operation.numberB = 4;
Context context = new Context(operation);
double result = context.getResult();
}
}
純粹的策略模式使得客戶端還需要處理一大堆的判斷,顯得很臃腫,可以將策略模式與簡單工廠模式結合,將判斷的代碼移到Context中,如下:
Context.class:
class Context{
private Operation operation;
public Context(String operator,String numberA,String numberB){
switch(operator){
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
}
operation.numberA = numberA;
operation.numberB = numberB;
}
public double getResult(){
return operation.getResult();
}
}
Client.class
public class Client{
public static void main(String[] args){
Context context = new Context("+",2,4);
double result = context.getResult();
}
}
4.總結
可以看到策略模式與簡單工廠模式非常非常相似~
策略模式與簡單工廠模式的區別:
簡單工廠模式:
Operation operation = OperationFactory.create("+",2,4);
double result = operation.getResult();
策略模式:
Context context = new Context("+",2,4);
double result = context.getResult();
策略模式中用戶只需要關心Context一個對象即可,簡單工廠模式有OperationFactory和Operation兩個對象需要用戶去了解。
策略模式中Context類不止可以生成對象,而且還暴露出方法可以讓客戶端直接調用對象的方法,爲客戶端提供一條龍服務~因此對客戶端來說,策略模式的封裝性更好。