策略模式
一个类的行为或其算法可以在运行期更改。众多算法相似的时候,使用if else引发过于复杂难以维护。
策略接口:
1 public interface Strategy { 2 3 int operation(int a, int b); 4 }
不同的策略:
1 public class OperationAdd implements Strategy { 2 3 @Override 4 public int operation(int a, int b) { 5 return a + b; 6 } 7 } 8 9 public class OperationSub implements Strategy { 10 11 @Override 12 public int operation(int a, int b) { 13 return a - b; 14 } 15 }
持有策略的上下文:
1 public class Context { 2 3 private Strategy strategy; 4 5 public Context(Strategy strategy) { 6 this.strategy = strategy; 7 } 8 9 public int executeStrategy(int a, int b) { 10 return strategy.operation(a, b); 11 } 12 }
测试类:
1 public class Main { 2 3 public static void main(String[] args) { 4 Context context = new Context(new OperationAdd()); 5 System.out.println(context.executeStrategy(1, 2)); 6 7 context = new Context(new OperationSub()); 8 System.out.println(context.executeStrategy(5, 3)); 9 } 10 }