策略模式-Strategy
概述
首先我们讲讲什么是策略模式
我们就拿写代码这个事情来举例,周末在家作为程序员我们还是想写会儿代码,这时候写代码这个就可能有很多个方式了:
1.先运动,再写代码
2.先看小说,再写代码
3.先学习,再写代码
而这些不同的方式就可以看做是我们程序员在周末想写代码这个事情的策略
1.使用策略模式可以避免使用多重条件语句
2.策略模式可以把部分公共代码转移到父类里面,从而避免重复的代码
3.策略模式可以提供相同行为的不同实现,用户可以根据不同的要求选择不同的策略实现
4.策略模式可以在不修改原代码的情况下,灵活增加新算法
类图
我们通过类图来看看

1.首先定义一个接口,Strategy
2.定义多个针对该接口的实现类
3.定义一个Context环境类,这个类有一个策略实现类的引用提供给用户进行使用
代码实现
package strategy;
/**
* 策略接口
* @author chengjian
* @date 2019/7/14
*/
public interface Strategy {
/**
* 策略执行的操作
* @author chengjian
* @date 2019/7/14
*/
void operate();
}
package strategy;
public class StrategyRead implements Strategy {
/**
* 策略执行的操作
*
* @author chengjian
* @date 2019/7/14
*/
public void operate() {
System.out.println("看会儿小说,再写程序!");
}
}
package strategy;
public class StrategySport implements Strategy {
/**
* 策略执行的操作
*
* @author chengjian
* @date 2019/7/14
*/
public void operate() {
System.out.println("运动一会儿,再写程序!");
}
}
package strategy;
public class StrategyStudy implements Strategy {
/**
* 策略执行的操作
*
* @author chengjian
* @date 2019/7/14
*/
public void operate() {
System.out.println("学习一会儿,再写程序");
}
}
package strategy;
/**
* 策略执行环境
* @author chengjian
* @date 2019/7/14
*/
public class StrategyContext {
private Strategy strategy;
public StrategyContext(Strategy strategy) {
this.strategy = strategy;
}
//执行
public void operate(){
strategy.operate();;
}
}
package strategy;
/**
* 执行锦囊
* @author chengjian
* @date 2019/7/14
*/
public class StrategyCoder {
/**
*写程序
* @author chengjian
* @date 2019/7/14
*/
public static void main(String[] args) {
StrategyContext strategyBags;
System.out.println("先运动");
strategyBags=new StrategyContext(new StrategySport());
strategyBags.operate();
System.out.println("先学习");
strategyBags=new StrategyContext(new StrategyStudy());
strategyBags.operate();
System.out.println("先学习");
strategyBags=new StrategyContext(new StrategyRead());
strategyBags.operate();
}
}