介绍
策略模式(Strategy Pattern) 也叫 政策模式(Policy Pattern)。指的是对象具备某个行为,但是在不同的场景中,该行为有不同的实现算法。比如有一个俩个数的计算场景需要四种加减乘除的具体实现需要落地。策略模式 使用的就是面向对象的继承和多态机制,从而实现同一行为在不同场景下具备不同实现。
目的
解决业务上多种情况(代码中的 if...eles)
优缺点
优点
1.算法可以自由切换。
2.避免使用多重条件判断。
3.扩展性良好。
缺点
1.策略类会增多。
2.所有策略类都需要对外暴露。
UML类图
实现
我们将创建一个定义活动的 Calculateor 接口和实现了 Calculateor 接口的实体策略类。Context 是一个使用了某种策略的类。 StrategyPatternMain,我们的演示类使用 Context 和策略对象来演示 Context 在它所配置或使用的策略改变时的行为变化。
1.创建一个抽象Calculateor。
/**
* 计算抽象类
* @author chenxinming
*/
public abstract class Calculateor {
/**
* 计算抽象方法
* @param num1
* @param num2
* @return
*/
public abstract int doOperation(int num1, int num2);
}
2.创建加、减、乘、除计算类实现接口的实体类。
/**
* 加法计算者
*
* @author chenxinming
*/
public class AddCalculateor extends Calculateor {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
/**
* 减法计算者
*
* @author chenxinming
*/
public class SubtractCalculateor extends Calculateor {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
/**
* 乘法计算者
*
*/
public class multiplyCalculateor extends Calculateor {
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
/**
* 除法计算者
*
* @author chenxinming
*/
public class DivideCalculateor extends Calculateor {
@Override
public int doOperation(int num1, int num2) {
return num1 / num2;
}
}
3.创建 Context 类。
public class Context {
//抽象计算者
private Calculateor calculateor;
public Context(Calculateor calculateor){
this.calculateor = calculateor;
}
//计算方法
public int executeStrategy(int num1, int num2){
return calculateor.doOperation(num1, num2);
}
}
4.使用 Context来查看当它改变策略 Calculateor 时的行为变化。
public class StrategyPatternMain {
public static void main(String[] args) {
Context context = new Context(new AddCalculateor());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new SubtractCalculateor());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new multiplyCalculateor());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
context = new Context(new DivideCalculateor());
System.out.println("10 / 5 = " + context.executeStrategy(10, 5));
}
}
5.计算结果
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2