对于不同的需求可能有不同的实现, 但这些实现还不能独立成为什么东西。 当把它们放到锦囊里面之后, 就成了一个个妙计了, 这就是策略。
策略模式其实和代理模式很像, 区别在于代理模式的代理同样需要具备被代理者的行为 - 即要实现和被代理者实现的同一接口或抽象类, 而策略模式中的“代理”仅仅是个皮囊而已。
这次我们一加减法为例:
先看策略接口
public interface Strategy {
double calc(double x, double y);
}
加减发的实现
public class PlusStrategy implements Strategy {
@Override
public double calc(double x, double y) {
return x + y;
}
}
public class MinusStrategy implements Strategy {
@Override
public double calc(double x, double y) {
return x - y;
}
}
然后要放到锦囊里面
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void execute(double x, double y) {
System.out.println(this.strategy.calc(x, y));
}
}
好啦,
pubic class Client{
public static void main(String[] args) {
double x = 100, y = 20.99;
Context context = new Context(new PlusStrategy());
System.out.println(x + " + " + y);
context.execute(x, y);
context = new Context(new MinusStrategy());
System.out.println(x + " - " + y);
context.execute(x, y);
}
}
执行结果:
引用
100.0 + 20.99
120.99
100.0 - 20.99
79.01
是不是很简单? 没错, 确实很简单。 那再来看看传说中的“策略枚举”吧
enum Calculator {
PLUS("+") {
@Override
public double calc(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double calc(double x, double y) {
return x - y;
}
};
private final String simble;
public String getSimble() {
return simble;
}
private Calculator(String simble) {
this.simble = simble;
}
@Override
public String toString() {
return this.simble;
}
protected abstract double calc(double x, double y);
}
客户端代码:
System.out.println(x + " " + Calculator.PLUS.simble + " " + y);
System.out.println(Calculator.PLUS.calc(x, y));
System.out.println(x + " " + Calculator.MINUS.simble + " " + y);
System.out.println(Calculator.MINUS.calc(x, y));
执行结果一样的:
引用
100.0 + 20.99
120.99
100.0 - 20.99
79.01