/** * @author yuyang * @DATE 2019/1/7 0007-9:12 * 抽象策略角色 */ public interface Strategy { int calc(int a,int b); }
/** * @author yuyang * @DATE 2019/1/7 0007-9:12
*具体策略模式 */ public class Addcalc implements Strategy { @Override public int calc(int a,int b) { return a+b; } }
/** * @author yuyang * @DATE 2019/1/7 0007-9:14
具体策略角色 */ public class Subtractcalc implements Strategy{ @Override public int calc(int a, int b) { return a-b; } }
/** * @author yuyang * @DATE 2019/1/7 0007-9:15
环境角色 */ public class Environment { Strategy strategy; public Environment(Strategy strategy) { this.strategy = strategy; } public int calc(int a,int b){ return strategy.calc(a,b); } }
/** * @author yuyang * @DATE 2019/1/7 0007-9:14
*/ public class Text { public static void main(String[] args) { Environment environment = new Environment(new Subtractcalc()); System.out.println(environment.calc(5,5)); } }