策略者模式

步骤 1
创建一个接口。
Strategy.java
public interface Strategy {
   public int doOperation(int num1, int num2);
}
步骤
2 创建实现接口的实体类。 OperationAdd.java public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } }
OperationSubstract.java
public class OperationSubstract implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 - num2; } }
OperationMultiply.java
public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } }
步骤
3 创建 Context 类。 Context.java public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } }
步骤
4 使用 Context 来查看当它改变策略 Strategy 时的行为变化。 StrategyPatternDemo.java public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
步骤
5 验证输出。 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50

 

posted @ 2019-04-02 22:18  y-xs  阅读(123)  评论(0编辑  收藏  举报