首先你需要一个接口,定义需要的行为方法,如下:
interface Strategy{
void algorithm();
}
然后你需要几个实现了这个接口的实现类,如下
public class Strategy1 implements Strategy{
void algorithm(){
System.out.println("this is the Strategy1 algorithm");
}
}
public class Strategy2 implements Strategy{
void algorithm(){
System.out.println("this is the Strategy2 algorithm");
}
}
最后在你需要这个实现类的客户端类定义这个接口的变量,在构造函数或者set方法中传进来具体的实现类复制给接口变量
接着定义客户端类的行为方法,这里面只需要调用接口的行为就可以了。
public class Context{
private Strategy strategy;
public Context(Strategy strategy){
this.strategy=strategy;
}
public void operation(){
this.strategy.algorithm();
}
}
至此,完成了策略模式最基本的实现形式,上一下官方图
策略模式的应用场景主要在于替换掉多if else的场景。结合反射+工厂模式或者map+工厂模式可以通过关键字应用对应的策略类从而避免if else使用,其实就是将选择推迟到了map中的查询和反射。