策略模式(Strategy)
定义:(它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会直接影响到用算法的客户。)
模式分析:
策略模式是一种定义一系列算法的模式,完成的工作相同,只是由于实现不同,所以以相同的方式调用,减少了各种算法类与使用算法类之间的耦合。
策略模式可以封装任何类型的规则,实践过程中,只要在分析过程中听到以不同的时间运用不同的业务规则,就可以考虑用策略模式。
简单来说:方法通过参数的不同,调用了各不相同的算法逻辑,得到了自己想要的结果。
结构图:
这个类图并不复杂,右边是策略接口以及它的实现类,左边会有一个上下文,这个上下文会拥有一个策略,而具体这个策略是哪一种,我们是可以随意替换的。
下面还是以一个计算器的代码为案例:
//抽象计算类
public interface OperationStategy {
BigDecimal operation(BigDecimal num1,BigDecimal num2);
}
//实现OperationStategy,加法实现类
public class OperationStategyAdd implements OperationStategy {
@Override
public BigDecimal operation(BigDecimal num1, BigDecimal num2) {
return num1.add(num2);
}
}
//减法实现类
public class OperationStategySub implements OperationStategy {
@Override
public BigDecimal operation(BigDecimal num1, BigDecimal num2) {
return num1.subtract(num2);
}
}
public class Context {
private OperationStategy operationStategy;
// 基本策略模式
// public Context(OperationStategy operationStategy){
// this.operationStategy = operationStategy;
// }
// 策略模式与简单工厂模式结合
public Context(OperationEnum operationEnum){
switch (operationEnum){
case ADD:
operationStategy = new OperationStategyAdd();
case SUB:
operationStategy = new OperationStategySub();
}
}
public BigDecimal operation(BigDecimal num1,BigDecimal num2){
return operationStategy.operation(num1,num2);
}
}
/**
* @Author: yhr
* @Date: 2018/7/27/027 10:23
* 实现简单计算器
* 策略模式()
* 应用场景:不同时间应用不同的业务规则
*/
public class RunMain {
public static void main(String[] args) {
//基本策略模式
//Context context = new Context(new OperationStategyAdd());
//策略模式与工厂模式结合
Context context = new Context(OperationEnum.ADD);
BigDecimal result = context.operation(new BigDecimal(3), new BigDecimal(2));
System.out.println(result);
}
}