01策略模式定义
策略模式对应于解决某一个问题的算法簇。例如,商场里的促销活动,不同时间应用不同的促销活动。 策略模式就是允许用户任意的选择不同的算法,同时可以方便算法簇的扩容。
02策略模式的实现
需要一个上下文对象Context,持有算法的引用。客户端通过调用Context,实现不同的算法。
03代码实现
/**
* 算法簇
*/
public interface Strategy {
void price(int price);
}
/**
* 策略类的实现
*
* @author Harvey
* @create 2018-04-06 下午11:40
**/
public class Strategy01 implements Strategy {
@Override
public void price(int price) {
System.out.println("促销方式1下的价格为:" + price * 0.8);
}
}
/**
* 上下文对象,用于使用策略对象
*
* @author Harvey
* @create 2018-04-06 下午11:42
**/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void price(int price) {
strategy.price(price);
}
}
调用方法
Strategy strategy = new Strategy01();
Context context = new Context(strategy);
context.price(100);
输出结果:
促销方式1下的价格为:80.0
04 策略模式的本质
分离算法,选择实现
05 应用场景
a) 选择不同的主题时 b) Spring中的Resource的资源实现