策略模式的本质:
分离算法,选择实现
package com;
public interface Strategy {
double caclPrice(double goodsPrice);
}
package com.impl;
import com.Strategy;
public class StrategyA implements Strategy {
@Override
public double caclPrice(double goodsPrice) {
System.out.println("普通客户没有折扣哦!");
return goodsPrice;
}
}
package com.impl;
import com.Strategy;
public class StrategyB implements Strategy {
@Override
public double caclPrice(double goodsPrice) {
System.out.println("VIP客户可以打8折哦!");
return goodsPrice * (1 - 0.2);
}
}
package com;
import com.Strategy;
public class Context {
private Strategy strategy;
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public double caclPrice(double goodsPrice){
return strategy.caclPrice(goodsPrice);
}
}
import com.Context;
import com.impl.StrategyA;
import com.impl.StrategyB;
public class Client {
public static void main(String[] args) {
Context context = new Context();
context.setStrategy(new StrategyA());
System.out.println(context.caclPrice(100));
context.setStrategy(new StrategyB());
System.out.println(context.caclPrice(100));
}
}
策略算法是相同行为的不同实现。
如果没有上下文,那么就需要客户端来直接与具体的策略交互,尤其是当需要提供一些公共功能,或者相关状态存储的时候,会大大增加客户端使用的难度。因此,引入上下文还是很必要的,有了上下文,这些工作就由上下文来完成了,客户端只需要与上下文交互就可以了,这样会让整个设计模式更独立、更有整体性,也让客户端更简单。