什么是策略模式?
策略模式(Strategy Pattern)属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
其主要目的是通过定义相似的算法,替换if else 语句写法,并且可以随时相互替换。
策略模式主要由这三个角色组成,接口,辅助类,实现类
- 接口:持有一个策略类的引用,提供给客户端使用。
- 辅助类:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
- 实现类:包装了相关的算法或行为。
实现举例
1. 定义接口
public interface ICalculator {
public int calculate(String exp);
}
2.定义辅助类
public abstract class AbstractCalculator {
public int[] split(String exp,String opt){
String array[] = exp.split(opt);
int arrayInt[] = new int[2];
arrayInt[0] = Integer.parseInt(array[0]);
arrayInt[1] = Integer.parseInt(array[1]);
return arrayInt;
}
}
3. 定义实现类
public class Plus extends AbstractCalculator implements ICalculator {
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"\\+");
return arrayInt[0]+arrayInt[1];
}
}
public class Minus extends AbstractCalculator implements ICalculator {
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"-");
return arrayInt[0]-arrayInt[1];
}
}
public class Multiply extends AbstractCalculator implements ICalculator {
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"\\*");
return arrayInt[0]*arrayInt[1];
}
}
由此实现了一个策略模式代码的编写。
优劣总结
1.策略模式优点
扩展性好,可以在不修改对象结构的情况下,为新的算法进行添加新的类进行实现。
灵活性好,可以对算法进行自由切换。
2.策略模式缺点
使用策略类变多,会增加系统的复杂度。
客户端必须知道所有的策略类才能进行调用。