一、定义

定义一组算法,并将每个算法封装起来,使得它们之间可以相互替换。策略模式让算法的变化独立于使用它的客户端。

二、类图表示

策略模式

三、实现

1、Strategy

package pattern.behavioral.strategy;

public abstract class Strategy {

	public abstract void algorithmInterface();
}


package pattern.behavioral.strategy;

public class ConcreteStrategyA extends Strategy{

	@Override
	public void algorithmInterface() {
		System.out.println("called ConcreteStrategyA.algorithmInterface()...");
	}

}


package pattern.behavioral.strategy;

public class ConcreteStrategyB extends Strategy {

	@Override
	public void algorithmInterface() {
		System.out.println("called ConcreteStrategyB.algorithmInterface()...");
	}

}


package pattern.behavioral.strategy;

public class ConcreteStrategyC extends Strategy {

	@Override
	public void algorithmInterface() {
		System.out.println("called ConcreteStrategyC.algorithmInterface()...");
	}

}

2、Context

package pattern.behavioral.strategy;

public class Context {

	private Strategy strategy;
	
	public Context(Strategy strategy) {
		this.strategy = strategy;
	}
	
	public Strategy getStrategy() {
		return strategy;
	}

	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}

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

四、使用

package pattern.behavioral.strategy;

public class Client {

	public static void main(String[] args) {
		Context context = new Context(new ConcreteStrategyA());
		context.contextInterface();
		
		System.out.println();
		
		context.setStrategy(new ConcreteStrategyB());
		context.contextInterface();
		
		System.out.println();
		
		context.setStrategy(new ConcreteStrategyC());
		context.contextInterface();
	}
}
  • 程序输出:
called ConcreteStrategyA.algorithmInterface()...

called ConcreteStrategyB.algorithmInterface()...

called ConcreteStrategyC.algorithmInterface()...

五、适用场合

  • 需要在不同的情况下使用不同的策略,或是在未来还有可能用其他方式实现时

  • 需要隐藏具体策略的实现,避免暴露给客户端复杂的具体实现细节

  • 当多个相关的类只是行为不同,需要在运行时动态选择要执行的行为的时候

  • 当一个类定义了多个行为,而且这些行为是在这个类的操作中以多个条件语句的形式出现时(将相关的条件分支移入各自的策略类中以代替条件语句)