策略模式是对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。
比如“三只松鼠”的官方旗舰店,有“优惠”的行为,但是有好几种优惠选择:满两件打7折,满199-100等。这些优惠选择就是实现了不同的算法。
又比如说,对两个数进行操作,可以有“加减乘除”四种不同的实现。
适用场景和优缺点 |
适用场景
(1)当一个系统中有许多类,它们之间的区别仅在于它们的行为,希望动态地让一个对象在许多行为中选择一种行为时
(2) 当一个系统需要动态地在几种算法中选择一种时
(3)当一个对象有很多的行为,不想使用多重的条件选择语句来选择使用哪个行为时
优点
(1)算法可以自由切换
(2)避免使用多重条件判断
(3)扩展性良好
缺点
(1)策略类会增多
(2)所有策略类都需要对外暴露
实现思路 |
类图
实现思路
(1)定义一个公共接口Strategy,里面有所有算法都要实现的公共方法。比如下面代码中,“运算接口”里面有一个“运算方法”。
public interface Icalculator{
public int calculate(String exp);
}
(2)定义具体的实现类ConcreteStragegy,并对公共方法进行实现。比如定义“减法”这个实现类,对“运算方法”进行实现。实现类一般为多个,在本文中有两个:减法、加法。
public class Minus extends AbstractCaculator implements Icalculator{
@Override
public int calculate(String exp){
int a[] =split(exp,"-");
return a[0]-a[1];
}
}
(3)定义一个环境类Context,来持有对Strategy类的引用,供测试类使用。至于为什么要有这个类,应该是为了把多个实现类中的公共东西抽取出来,减少代码的冗余。
public class AbstractCaculator{
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;
}
}
(4)写测试类,计算2+3
public class StrategyTest{
public static void main(String[] args){
String exp="2+3";
Icalculator cal=new Plus();
int result=cal.calculate(exp);
sout(result);
}
}
代码实现 |
策略模式的代码实现如下:
//定义一个公共接口,里面有一个公共方法
public interface Icalculator{
public int calculate(String exp);
}
//分别对其进行实现
public class Minus extends AbstractCaculator implements Icalculator{
@Override
public int calculate(String exp){
int a[] =split(exp,"-");
return a[0]-a[1];
}
}
public class Plus extends AbstractCaculator implements Icalculator{
@Override
public int calculate(String exp){
int a[] =split(exp,"\\+");
return a[0]+a[1];
}
}
public class AbstractCaculator{
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;
}
}
//测试类
public class StrategyTest{
public static void main(String[] args){
String exp="2+3";
// 这一句运用到了多态
Icalculator cal=new Plus();
int result=cal.calculate(exp);
sout(result);
}
}
解释:
策略模式中,系统只提供不同算法的实现,到底选择哪种算法,是由测试类决定的。就像你去肯德基吃饭,他们有好几种套餐供选择,到底选择哪个,是由你自己决定的。