设计模式(12)-策略模式
2018-02-28 16:07
288 查看
定义
将具体的策略实现放入策略容器中,实现策略的灵活调用和替换.
1.策略接口
2.策略实现
3.策略容器类
4.运行
输出:
5.枚举策略
将具体的策略实现定义在枚举中,书写更为简洁.
运行:
将具体的策略实现放入策略容器中,实现策略的灵活调用和替换.
1.策略接口
public interface IStrategy { //对a和b进行运算,返回结果 public int calculate(int a,int b); }
2.策略实现
public class AddStrategy implements IStrategy{ @Override //加法运算 public int calculate(int a, int b) { return a+b; } }
public class SubStrategy implements IStrategy{ @Override //减法运算 public int calculate(int a, int b) { return a-b; } }
3.策略容器类
public class Context { private IStrategy strategy; public Context(IStrategy strategy){ this.strategy = strategy; } //原样实现strategy的方法 public int calculate(int a,int b){ return strategy.calculate(a, b); } }
4.运行
public class Client { public static void main(String[] args) { Context addContext = new Context(new AddStrategy()); Context subContext = new Context(new SubStrategy()); System.out.println("2+3= "+addContext.calculate(2, 3)); System.out.println("2-3= "+subContext.calculate(2, 3)); } }
输出:
2+3= 5 2-3= -1
5.枚举策略
将具体的策略实现定义在枚举中,书写更为简洁.
public enum Calculator { //枚举对象必须写在最前面 ADD("+") { @Override public int calculate(int a, int b) { return a+b; } }, SUB("-") { @Override public int calculate(int a, int b) { return a-b; } }; //构造函数,value属性在构造时传入. private Calculator(String value){ this.value = value; } private String value; //返回枚举的value属性值 public String getValue(){ return this.value; } //抽象方法,枚举对象必须实现 public abstract int calculate(int a, int b); }
运行:
public class Client { public static void main(String[] args) { System.out.println("2+3= "+Calculator.ADD.calculate(2, 3)); System.out.println("2-3= "+Calculator.SUB.calculate(2, 3)); } }
相关文章推荐
- 23种设计模式(12):策略模式
- 设计模式利剑12-策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 设计模式12:策略模式
- 23种设计模式(12):策略模式
- 设计模式-12-策略模式
- 23种设计模式(12):策略模式
- 23种设计模式-12-策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 设计模式之12策略模式(笔记)
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式
- 23种设计模式(12):策略模式