策略设计模式
策略模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。
-
定义了一族算法(业务规则);
-
封装了每个算法,算法之间在客户端是各自独立的;
-
这族的算法可互换代替(interchangeable)。
适用性
-
许多相关类仅仅是行为不同。
-
需要使用一个算法的不同实现。
-
算法使用了客户不应该知道的数据。策略模式可以避免暴露复杂的、与算法相关的数据结构。
-
一个类定义了很多行为,而且这些行为在这个类里的操作以多个条件语句的形式出现。策略模式将相关的条件分支移入它们各自的 Strategy 类中以代替这些条件语句。
UML
例子
首先定义策略接口:
/**
* 一个具体的策略应该实现该接口,并且一个上下文对象Context应该持有该接口的引用
* @author dengfengdecao
*
*/
public interface Strategy {
void execute();
}
该接口定义了一个抽象的算法。
有了策略接口,接下来就是一个个具体的策略了:
public class FirstStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called FirstStrategy.execute()");
}
}
public class SecondStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called SecondStrategy.execute()");
}
}
public class ThirdStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called ThirdStrategy.execute()");
}
}
以上定义了三个具体策略。接下来需要一个上下文对象:
/**
* 配置具体的策略并持有一个Strategy接口的引用
* @author dengfengdecao
*
*/
public class Context {
Strategy strategy;
public Context(Strategy strategy) {
super();
this.strategy = strategy;
}
public void execute() {
this.strategy.execute();
}
}
在这个对象里,引用了策略接口,并定义了一个构造函数来传递具体的策略对象。
最后在客户端测试:
public class StrategyClient {
public static void main(String[] args) {
Context context;
// 以下运行三个不同的策略
context = new Context(new FirstStrategy());
context.execute();
context = new Context(new SecondStrategy());
context.execute();
context = new Context(new ThirdStrategy());
context.execute();
}
}
结果:
一个更具体的例子可参考此文:http://blog.csdn.net/defonds/article/details/16832081