定义
定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。策略模式模式使得算法可独立于使用它的客户而独立变化。
实现
1.定义抽象策略类
public interface Strategy {
int doSomething(int a,int b);
}
2.定义具体的策略
public class Add implements Strategy{
@Override
public int doSomething(int a, int b) {
return a+b;
}
}
public class Multiple implements Strategy{
@Override
public int doSomething(int a, int b) {
return a*b;
}
}
3.定义操作类
public class Compute {
Strategy strategy;
public Compute(Strategy strategy){
this.strategy = strategy;
}
public int compute(int a,int b){
return strategy.doSomething(a,b);
}
}
4.客户端调用
Compute compute = new Compute(new Add());
System.out.println(compute.compute(3,6));