創建一個能夠根據所傳遞的參數對象的不同而具有不同行為的方法
-
要執行的算法固定不變,封裝到一個類(Context)中
-
策略就是傳遞進去的參數對象,它包含執行代碼
-
策略接口
/**
* 策略接口
*/
public interface IStrategy {
String name();
/**
* 具體邏輯(算法)
* @param str
* @return
*/
String Arithmetic(String str);
}
- 具體實現
public class Downcase implements IStrategy {
public String name() {
return getClass().getSimpleName();
}
public String Arithmetic(String str) {
return str.toLowerCase();
}
}
public class UpCase implements IStrategy {
public String name() {
return getClass().getSimpleName();
}
public String Arithmetic(String str) {
return str.toUpperCase();
}
}
public class Splitter implements IStrategy {
public String name() {
return getClass().getSimpleName();
}
public String Arithmetic(String str) {
return Arrays.toString(str.split(" "));
}
}
- 封裝邏輯(算法)
/**
* 策略模式通過組合的方式實現具體算法
* 其要執行的算法不變,封裝到一個類(Context)中
*/
public class Context {
private IStrategy mStrategy;
/**
* 將抽象接口的實現傳遞給組合對象
* @param strategy
*/
public Context(IStrategy strategy){
this.mStrategy = strategy;
}
/**
* 封裝邏輯(算法)
* @param s
*/
public void doAction(String s){
System.out.println(mStrategy.name());
System.out.println(this.mStrategy.Arithmetic(s));
}
}
- 測試
public static String s="Disagreement with beliefs is by definition incorrect";
public static void main(String[] args){
IStrategy is = new UpCase();
Context c = new Context(is);
c.doAction(s);
IStrategy isd = new Downcase();
Context c2 = new Context(isd);
c2.doAction(s);
IStrategy iss = new Splitter();
Context c3 = new Context(iss);
c3.doAction(s);
}
