1.定义
定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于客户。
2.类图
3.测试代码
算法接口(抽象策略类)
public interface Strategy {
int operate(int a, int b);
}
加法策略类
/**
* 加法策略类
*/
public class AddStrategy implements Strategy {
@Override
public int operate(int a, int b) {
return a + b;
}
}
减法策略类
/**
* 减法策略类
*/
public class SubStrategy implements Strategy {
@Override
public int operate(int a, int b) {
return a - b;
}
}
乘法策略类
/**
* 乘法策略类
*/
public class MultStrategy implements Strategy {
@Override
public int operate(int a, int b) {
return a * b;
}
}
除法策略类
/**
* 乘法策略类
*/
public class DivStrategy implements Strategy {
@Override
public int operate(int a, int b) {
return a / b;
}
}
计算器类
/**
* 计算器类
* 通过动态的传入对应策略来实现计算最终结果
*/
public class Calculator {
Strategy strategy;
Calculator(Strategy strategy) {
this.strategy = strategy;
}
int execute(int a, int b) {
return strategy.operate(a, b);
}
}
测试入口
public class InitMain {
public static void main(String[] args) {
Calculator calAdd = new Calculator(new AddStrategy());
System.out.println("this is add = " + calAdd.execute(5, 10));
Calculator calSub = new Calculator(new SubStrategy());
System.out.println("this is sub = " + calSub.execute(5, 10));
Calculator calMult = new Calculator(new MultStrategy());
System.out.println("this is mult = " + calMult.execute(5, 10));
Calculator calDiv = new Calculator(new DivStrategy());
System.out.println("this is div = " + calDiv.execute(5, 10));
}
}
输出如下:
this is add = 15
this is sub = -5
this is mult = 50
this is div = 0
4.总结
策略模式把系统中会发生变化的部分抽出来封装为具体的策略类,调用时候通过动态的传入策略类来实现不同的算法。通过对象组合的方式使算法的变化独立于客户的系统,从而实现解耦。