什么是策略模式
定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
策略模式由三种角色组成
策略模式应用场景
策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同接口的独立的类中,从而使得它们之间可以相互替换。策略模式使得算法或逻辑可以在不影响到客户端的情况下发生变化。说到策略模式就不得不提及OCP(Open Closed Principle) 开闭原则,即对扩展开放,对修改关闭。策略模式的出现很好地诠释了开闭原则,有效地减少了分支语句。
解决问题的代码:
之前我们写代码
:不停的判断业务维护起来比较麻烦
public void getPrice(String leve){
Long price = null;
if(leve.equals("铂金会员")){
price = (long)100*100;
}else if(leve.equals("黄金会员")){
price = (long) 100*150;
}else if(leve.equals("普通会员")){
price = (long)100*200;
}
}
使用策略模式写代码
package mayi02.may02.strategy;
//策略模式dinginess抽象公共算法
abstract class Strategy {
abstract void algorithmInterface();
}
//初级会员,针对算法A算法
class StrategyA extends Strategy{
@Override
void algorithmInterface() {
System.out.println("初级会员,针对算法A算法");
}
}
//中级会员,针对算法B算法
class StrategyB extends Strategy{
@Override
void algorithmInterface() {
System.out.println("中级会员,针对算法B算法");
}
}
class Context{
private Strategy strategy;
Context(Strategy strategy){
this.strategy = strategy;
}
void algorithmInterface(){
strategy.algorithmInterface();
}
}
//高级会员,针对算法C算法
class StrategyC extends Strategy{
@Override
void algorithmInterface() {
System.out.println("高级会员,针对算法C算法");
}
}
public class StrategyTest {
public static void main(String[] args) {
Context context = null;
Strategy strategyA = new StrategyA();
context = new Context(strategyA);
context.algorithmInterface();
Strategy strategyB = new StrategyB();
context = new Context(strategyB);
context.algorithmInterface();
Strategy strategyC = new StrategyC();
context = new Context(strategyC);
context.algorithmInterface();
}
}