java设计模式之行为型模式-策略模式

来源:互联网 发布:剑三明教脸型数据 编辑:程序博客网 时间:2024/04/28 07:35

策略设计模式

策略模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。

  • 定义了一族算法(业务规则);

  • 封装了每个算法,算法之间在客户端是各自独立的;

  • 这族的算法可互换代替(interchangeable)。


适用性

  1. 许多相关类仅仅是行为不同。

  2. 需要使用一个算法的不同实现。

  3. 算法使用了客户不应该知道的数据。策略模式可以避免暴露复杂的、与算法相关的数据结构。

  4. 一个类定义了很多行为,而且这些行为在这个类里的操作以多个条件语句的形式出现。策略模式将相关的条件分支移入它们各自的 Strategy 类中以代替这些条件语句。

UML


例子

首先定义策略接口:

  1. /**
  2. * 一个具体的策略应该实现该接口,并且一个上下文对象Context应该持有该接口的引用
  3. * @author dengfengdecao
  4. *
  5. */
  6. public interface Strategy {
  7. void execute();
  8. }

该接口定义了一个抽象的算法。

有了策略接口,接下来就是一个个具体的策略了:

  1. public class FirstStrategy implements Strategy {
  2. public void execute() {
  3. // 在这里实现具体得算法策略
  4. System.out.println("Called FirstStrategy.execute()");
  5. }
  6. }

  1. public class SecondStrategy implements Strategy {
  2. public void execute() {
  3. // 在这里实现具体得算法策略
  4. System.out.println("Called SecondStrategy.execute()");
  5. }
  6. }

  1. public class ThirdStrategy implements Strategy {
  2. public void execute() {
  3. // 在这里实现具体得算法策略
  4. System.out.println("Called ThirdStrategy.execute()");
  5. }
  6. }

以上定义了三个具体策略。接下来需要一个上下文对象:

  1. /**
  2. * 配置具体的策略并持有一个Strategy接口的引用
  3. * @author dengfengdecao
  4. *
  5. */
  6. public class Context {
  7. Strategy strategy;
  8. public Context(Strategy strategy) {
  9. super();
  10. this.strategy = strategy;
  11. }
  12. public void execute() {
  13. this.strategy.execute();
  14. }
  15. }

在这个对象里,引用了策略接口,并定义了一个构造函数来传递具体的策略对象。

最后在客户端测试:

  1. public class StrategyClient {
  2. public static void main(String[] args) {
  3. Context context;
  4. // 以下运行三个不同的策略
  5. context = new Context(new FirstStrategy());
  6. context.execute();
  7. context = new Context(new SecondStrategy());
  8. context.execute();
  9. context = new Context(new ThirdStrategy());
  10. context.execute();
  11. }
  12. }

结果:



一个更具体的例子可参考此文:http://blog.csdn.net/defonds/article/details/16832081 

0 0