##简介
属于对象的行为模式,其用意是针对一组算法,将每个算法封装到具有共同接口的独立的类中,从而使得他们可以相互替换,策略模式使得算法可以再不影响到客户端的情况下发生变化
##包含角色
###抽象策略角色
给出了所有的具体策略类所需的接口
###具体策略角色
包装了相关的算法或行为
###环境角色
持有一个Strategy类的引用
##UML类图
##java实现
###1.抽象策略角色
/**
* @program: pattern
* @description: 抽象策略角色
* @author: chengqj
* @create: 2018-07-30 18:28
**/
public interface Strategy {
void algorithmInterface();
}
###2.具体策略角色
/**
* @program: pattern
* @description: Strategy实现类A
* @author: chengqj
* @create: 2018-07-30 18:28
**/
public class StrategyA implements Strategy{
@Override
public void algorithmInterface() {
System.out.println("StrategyA");
}
}
###环境角色
/**
* @program: pattern
* @description: 环境角色
* @author: chengqj
* @create: 2018-07-30 18:30
**/
public class Client {
private Strategy strategy;
public Client(Strategy strategy) {
this.strategy = strategy;
}
public void algorithmInterface(){
strategy.algorithmInterface();
}
public static void main(String[] args) {
Client client = new Client(new StrategyA());
client.algorithmInterface();
}
}
##优缺点
###优点
1、 策略模式提供了管理相关的算法族的办法。
2、 策略模式提供了可以替换继承关系的办法。
3、 使用策略模式可以避免使用多重条件转移语句。
###缺点
1、 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。
2、 策略模式造成很多的策略类,每个具体策略类都会产生一个新类。