1 策略模式的定义
The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
策略模式定义了一系列的算法,将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。也就是说,客户可以根据不同的情况选择不同的策略来应对某种场景。
策略模式属于对象行为型模式,主要针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响 到客户端的情况下发生变化。通常,策略模式适用于当一个应用程序需要实现一种特定的服务或者功能,而且该程序有多种实现方式时使用。
2 策略模式涉及的三个类
策略模式类图:
2.1 抽象策略类
定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。
2.2 具体策略类
现了Strategy定义的接口,提供具体的算法实现。
2.3 上下文类
包含了抽象策略类的引用。
3 代码实现
public interface IStrategy {
public void resolve();
}
public class ByBus implements IStrategy {
@Override
public void resolve() {
// TODO Auto-generated method stub
System.out.println("坐公交回家...");
}
}
public class ByFoot implements IStrategy {
@Override
public void resolve() {
// TODO Auto-generated method stub
System.out.println("徒步回家...");
}
}
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy) {
// TODO Auto-generated constructor stub
this.strategy=strategy;
}
public void goHome() {
strategy.resolve();
}
}
public class TestStrategy {
public static void main(String[] args) {
Context context;
//用户根据不同的情况,来选择不同的策略
System.out.println("天朗气清,决定徒步回家...");
context=new Context(new ByFoot());
context.goHome();
System.out.println("阴云密布,还是坐车回家的好...");
context=new Context(new ByBus());
context.goHome();
}
}
4 JDK中的典型应用
java.util.Comparator#compare()