策略模式:定义了不同的算法,分别封装起来,让他们可以互相替换,即使算法变化了,也不会影响到使用算法的用户;
简单解释:很像一个计算器,我输入两个数字,然后按加号你就给我计算和,我按乘法你就给我计算乘积,内部算法客户端不关注,我就告诉你我想做怎样的计算,你去给我计算吧!和工厂方法有一点像,
应用场景:立马就想到解除多个if else if 的场景了
//定义策略,提供一个方法供具体策略俩实现
public abstract class Strategy {
public abstract void calculate();
}
// 具体算法开始实现
public class StrategyAA extends Strategy {
@Override
public void calculate() {
System.out.println("实现算法A");
}
}
public class StrategyBB extends Strategy {
@Override
public void calculate() {
System.out.println("实现算法B");
}
}
//用一个context类来维护对抽象算法类Strategy对象的引用
public class Context {
Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void doWork(){
strategy.calculate();
}
}
开始测试:
public class Test1 {
public static void main(String[] args) {
Context context = null;
context = new Context(new StrategyAA());
context.doWork();
context = new Context(new StrategyBB());
context.doWork();
}
}
但是从上面测试类1的代码我们发现是在客户端判断是用什么算法,现在我们想把这个判断交由其他类处理,于是就有了下面的策略模式与简单工厂结合的方法。
public class Context2 {
Strategy strategy = null;
public Context2(String type){
switch (type){
case "A": strategy = new StrategyAA();
break;
case "B": strategy = new StrategyBB();
break;
}
}
public void ContrxtInterface(){
strategy.AlgorithmInterface();
}
}
//或者
public class Context2 {
static Map<String, Strategy> operationMap = new HashMap<>();
static {
operationMap.put("A", new StrategyAA());
operationMap.put("B", new StrategyBB());
}
public Context2(String type){
strategy = operationMap.get(type);
}
public void doWork(){
strategy.calculate();
}
}
public class Text2 {
public static void main(String[] args) {
Context2 context2A = new Context2("A");
context2A.doWork();
Context2 context2B = new Context2("B");
context2B.doWork();
}
}