1.什么是策略模式?
定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

说到策略模式就不得不提及OCP(Open Closed Principle) 开闭原则,即对扩展开放,对修改关闭。策略模式的出现很好地诠释了开闭原则,有效地减少了分支语句。

2.策略模式代码(解释:避免了频繁地在代码后面加if else )
此代码通过模拟不同会员购物车打折力度不同分为三种策略,初级会员,中级会员,高级会员。

//策略模式 定义抽象方法 所有支持公共接口
abstract class Strategy {

	// 算法方法
	abstract void algorithmInterface();

}

class StrategyA extends Strategy {

	@Override
	void algorithmInterface() {
		System.out.println("算法A");

	}

}

class StrategyB extends Strategy {

	@Override
	void algorithmInterface() {
		System.out.println("算法B");

	}

}

class StrategyC extends Strategy {

	@Override
	void algorithmInterface() {
		System.out.println("算法C");

	}

}
// 使用上下文维护算法策略

class Context {
	Strategy strategy;
	public Context(Strategy strategy) {
		this.strategy = strategy;
	}

	public void algorithmInterface() {
		strategy.algorithmInterface();
	}

}

class ClientTestStrategy {
	public static void main(String[] args) {
		Context context;
		context = new Context(new StrategyA());
		context.algorithmInterface();
		context = new Context(new StrategyB());
		context.algorithmInterface();
		context = new Context(new StrategyC());
		context.algorithmInterface();
	}
}