Java实现策略模式
策略模式的编写步骤:
1. 对策略对象定义一个公共接口;
2. 编写策略类,该类实现了上面的公共接口;
3. 在使用策略对象的类中保存一个对策略对象的引用;
4. 在使用策略对象的类中,实现对策略对象的set和get方法(注入)或者使用构造方法完成赋值
代码实例实现简单的加减乘除运算。
策略接口:
public interface Strategy { public int calculate(int a, int b); }
策略类:
public class AddStrategy implements Strategy{ public int calculate(int a, int b) { return a + b; } } public class SubstractStrategy implements Strategy{ public int calculate(int a, int b) { return a - b; } } public class MultiplyStrategy implements Strategy{ public int calculate(int a, int b) { return a * b; } } public class DivideStrategy implements Strategy{ public int calculate(int a, int b) { return a / b; } }
使用策略模式的类:
public class Environment { private Strategy strategy; public Environment(){} public Environment(Strategy strategy){ this.strategy = strategy; } public Strategy getStrategy() { return strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public int calculate(int a, int b){ return this.strategy.calculate(a, b); } public int calculate(int a, int b, Strategy strategy){ return strategy.calculate(a, b); } }
具体业务客户端:
public class Client { public static void main(String[] args) { Environment environment = new Environment(new AddStrategy()); System.out.println(environment.calculate(5, 3)); environment.setStrategy(new SubstractStrategy()); System.out.println(environment.calculate(5, 3)); System.out.println(environment.calculate(2, 3, new MultiplyStrategy())); System.out.println(environment.calculate(6, 3, new DivideStrategy())); } }
时间: 2024-12-17 08:13:25