策略模式定义了算法族,分别封装起来,让他们之间相互替换,此模式让算法的变化独立与使用算法的客户
良好的oo设计必须具备可复用,可扩充,可维护
策略模式的使用场景:
1.针对同一类型问题的多种处理方式,仅仅是具体行为有差别时;
2.需要安全地封装多种同一类型的操作时;
3.出现同一抽象类有多个子类,而又需要使用 if-else 或者 switch-case 来选择具体子类时。
这个模式涉及到三个角色:
环境(Context)角色:持有一个Strategy的引用。
抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。
抽象策略类
public interface Strategy {
/**
* 策略方法
*/
public void strategyInterface();
}
- 1
- 2
- 3
- 4
- 5
- 6
具体策略类
public class ConcreteStrategyA implements Strategy {
@Override
public void strategyInterface() {
//相关的业务
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class ConcreteStrategyB implements Strategy {
@Override
public void strategyInterface() {
//相关的业务
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
环境角色类
public class Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy 具体策略对象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextInterface(){
strategy.strategyInterface();
}
}