在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为。
如何解决:将这些算法封装成一个一个的类,任意地替换。
关键代码:实现同一个接口。
demo中的UML图如下:
具体代码实现,策略基类:
/**
* @author Shuyu.Wang
* @package:com.shuyu.strategy
* @className:
* @description:策略模式通用接口
* @date 2018-11-08 16:31
**/
public interface Strategy {
double operation(double a,double b );
}
相关实现类:
/**
* @author Shuyu.Wang
* @package:com.shuyu.strategy
* @description:加法实现类
* @date 2018-11-08 16:44
**/
public class OperationAdd implements Strategy{
@Override
public double operation(double a, double b) {
return a+b;
}
}
/**
* @author Shuyu.Wang
* @package:com.shuyu.strategy
* @description:乘法计算类
* @date 2018-11-08 16:47
**/
public class OperationMul implements Strategy{
@Override
public double operation(double a, double b) {
return a-b;
}
}
/**
* @author Shuyu.Wang
* @package:com.shuyu.strategy
* @description:减法类
* @date 2018-11-08 16:46
**/
public class OperationSub implements Strategy{
@Override
public double operation(double a, double b) {
return a-b;
}
}
结合上下文的Context:
/**
* @author Shuyu.Wang
* @package:com.shuyu.strategy
* @description:
* @date 2018-11-08 17:10
**/
public class Context {
Strategy strategy = null;
public Context(Strategy strategy ) {
this.strategy=strategy;
}
public double operation(double a,double b){
return strategy.operation(a, b);
}
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class StrategyApplicationTests {
@Test
public void contextLoads() {
Context context=new Context(new OperationAdd());
System.out.println(context.operation(10,5));
context=new Context(new OperationSub());
System.out.println(context.operation(10,5));
}
}
运行结果如下:
15.0
5.0
git代码地址:https://github.com/iot-wangshuyu/designpatterns/tree/master/strategy