策略模式的定義:
策略模式定義了一系列的算法,並將每一個算法封裝起來,而且使它們還可以相互替換,策略模式讓算法獨立於使用它的客戶而獨立變化。
策略模式使這些算法在客戶端調用它們的時候能夠互不影響地變化。
策略模式的意義:
策略模式使開發人員能夠開發出由許多可替換的部分組成的軟件,並且各個部分之間是低耦合的關系。
低耦合的特性使軟件具有更強的可擴展性,易於維護;更重要的是,它大大提高了軟件的可重用性。
策略模式中有三個對象:
環境對象(Context):該類中實現了對抽象策略中定義的接口或者抽象類的引用。
抽象策略對象(Strategy):它可由接口或抽象類來實現。
具體策略對象(ConcreteStrategy):它封裝了實現同不功能的不同算法。
三者之間的關系可以用下圖來表示:

策略模式的實現:
1.對策略對象定義一個公共接口。
2.編寫策略類,該類實現了上面的公共接口。
3.在使用策略對象的類中保存一個對策略對象的引用。
4.在使用策略對象的類中,實現對策略對象的set和get方法或者使用構造方法完成賦值。
具體代碼實現:
定義一個接口( 抽象策略),定義一個方法用於對兩個整數進行運算
1 public interface Strategy {
2
3 public abstract int calculate(int a,int b);
4 }
定義具體的算法類,實現兩個整數的加減乘除運算,但是外部調用形式需要符合接口的定義
實現加法運算
1 public class AddStrategy implements Strategy{
2
3 @Override
4 public int calculate(int a, int b) {
5
6 return a+b;
7 }
8
9 }
實現減法運算
1 public class SubstractStrategy implements Strategy{
2
3 @Override
4 public int calculate(int a, int b) {
5
6 return a-b;
7 }
8
9 }
實現乘法運算
1 public class MultiplyStrategy implements Strategy {
2
3 @Override
4 public int calculate(int a, int b) {
5
6 return a*b;
7 }
8
9 }
實現除法運算
1 public class DivisionStrategy implements Strategy{
2
3 @Override
4 public int calculate(int a, int b) {
5 if(b!=0){
6
7 return a/b;
8 }
9 else {
10 throw new RuntimeException("除數不能為零");
11 }
12 }
13
14 }
定義具體的環境角色,持有Strategy接口的引用,並且有get和set方法可以完成策略更換。在環境角色中調用接口的方法完成動作。
1 public class Context {
2
3 private Strategy strategy;
4
5 public Context(Strategy strategy) {
6 super();
7 this.strategy = strategy;
8 }
9
10 public Strategy getStrategy() {
11 return strategy;
12 }
13
14 public void setStrategy(Strategy strategy) {
15 this.strategy = strategy;
16 }
17 public int calculate(int a,int b){
18 return strategy.calculate(a, b);
19 }
20 }
這樣在客戶端在調用時,只需向環境角色設置相應的算法類,然后就可以得到相應的結果。
1 public class StrategyTest {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7
8 //加法
9 Context context=new Context(new AddStrategy());
10 System.out.println(context.calculate(10, 5));
11 //減法
12 Context context2=new Context(new SubstractStrategy());
13 System.out.println(context2.calculate(3, 2));
14 //乘法
15 Context context3=new Context(new MultiplyStrategy());
16 System.out.println(context3.calculate(6, 8));
17 //除法
18 Context context4=new Context(new DivisionStrategy());
19 System.out.println(context4.calculate(90, 9));
20 }
21
22 }
策略模式的缺點:

