策略模式(Strategy模式)是行为模式之一,它对一系列的算法加以封装,为所有算法定义一个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用来平滑地处理算法的切换 。切换算法不会影响使用算法的客户。
下面是在 程杰《大话设计模式》中截的图(书写的特别有意思),来描述策略模式的结构
Strategy 是定义一个算法的公共接口;
然后算法A、B、C implements Strategy 实现具体的算法;
Context维护一个Strategy对象的引用,是策略的外部封装类,或者说策略的容器类。根据不同策略执行不同的行为。
下面来看代码:
1、Strategy接口
public interface Strategy {
//加密
public void encrypt();
}
2、具体算法实现类
public class MD5Strategy implements Strategy{
public void encrypt() {
System.out.println("执行MD5加密");
}
}
public class MDSStrategy implements Strategy{
public void encrypt() {
System.out.println("执行MDS加密");
}
}
3、上下文对象
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void encrypt() {
this.strategy.encrypt();
}
}
4、客户端使用
public class MainClass {
public static void main(String[] args) {
// 客户端确定算法
Context context = new Context(new MDSStrategy());
context.encrypt();
}
}
总结:策略模式首先确定一个算法家族。他们都有一个共同的行为,但是达成行为的动作不一样,客户度通过策略的上下文的外部封装类来决定引用哪一种算法。
下面是程杰的 大鸟总结: