1 //策略類,定義所有支持的算法的公共接口 2 public abstract class Strategy { 3 public abstract void algorithmMethod(int numberA,int numberB); 4 }
1 //具體策略類,封裝了具體的算法或行為,繼承於Strategy 2 //用於加法的算法 3 public class ConcreteStrategyAdd extends Strategy { 4 5 @Override 6 public void algorithmMethod(int numberA,int numberB) { 7 System.out.println(numberA+" + "+numberB+" = "+(numberA+numberB)+";"); 8 } 9 10 }
1 //具體策略類,封裝了具體的算法或行為,繼承於Strategy 2 //用於乘法的算法 3 public class ConcreteStrategyMul extends Strategy { 4 5 @Override 6 public void algorithmMethod(int numberA,int numberB) { 7 System.out.println(numberA+" * "+numberB+" = "+(numberA*numberB)+";"); 8 } 9 10 }
1 //具體策略類,封裝了具體的算法或行為,繼承於Strategy 2 //用於兩個數相減的算法 3 public class ConcreteStrategySub extends Strategy { 4 5 @Override 6 public void algorithmMethod(int numberA,int numberB) { 7 System.out.println(numberA+" - "+numberB+" = "+(numberA-numberB)+";"); 8 } 9 10 }
Context中改動了一些代碼,和簡單工廠模式結合使用:
1 //Context上下文,用一個ConcreteStrategy來配置,維護一個對Strategy對象的引用 2 public class Context { 3 private Strategy strategy; 4 5 // 構造方法,注意,參數不是具體的算法策略對象,而是一個字符串,表示策略的類型 6 public Context(String strategyType) { 7 8 /** 9 * 將實例化具體策略的過程由客戶端轉移到Context類中,簡單工廠的應用 10 */ 11 switch (strategyType) { 12 case "add": 13 strategy = new ConcreteStrategyAdd(); 14 break; 15 case "sub": 16 strategy = new ConcreteStrategySub(); 17 break; 18 case "mul": 19 strategy = new ConcreteStrategyMul(); 20 break; 21 } 22 23 } 24 25 // 根據具體的策略對象,調用其算法的方法 26 public void contextInterface(int numberA, int numberB) { 27 strategy.algorithmMethod(numberA, numberB); 28 } 29 30 }
測試類:測試類中注釋掉的代碼是沒有結合簡單工廠模式的時候在客戶端寫的代碼。
1 public class Test { 2 public static void main(String[] args) { 3 Context context; 4 // 我想使用加法算法 5 /*context = new Context(new ConcreteStrategyAdd()); 6 context.contextInterface(5, 4);*/ 7 context = new Context("add"); 8 context.contextInterface(5, 4); 9 10 // 我想使用減法算法 11 /*context = new Context(new ConcreteStrategySub()); 12 context.contextInterface(5, 4);*/ 13 context = new Context("sub"); 14 context.contextInterface(5, 4); 15 16 // 我想使用乘法算法 17 /*context = new Context(new ConcreteStrategyMul()); 18 context.contextInterface(5, 4);*/ 19 context = new Context("mul"); 20 context.contextInterface(5, 4); 21 } 22 }
測試結果:
5 + 4 = 9;
5 - 4 = 1;
5 * 4 = 20;
UML圖: