14.Strategy-策略模式

来源:互联网 发布:中拍协网络拍卖平台首 编辑:程序博客网 时间:2024/06/18 14:34

Strategy 策略模式

  • 策略模式:
    也称为政策模式(Policy)。策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
    这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有算法,
    减少各种算法类与使用类之间的耦合。策略模式是一种对象行为型模式。

  • 结构图:
    Strategy_structure

  • 示例类图:
    Strategy_uml

  • 示例代码:

// Strategypublic interface Operation {    public int doOperation(int x, int y);}// ConcreteStrategypublic class OperationAdd implements Operation {    @Override    public int doOperation(int x, int y) {        return x + y;    }}public class OperationMultiply implements Operation {    @Override    public int doOperation(int x, int y) {        return x * y;    }}public class OperationSubstract implements Operation {    @Override    public int doOperation(int x, int y) {        return x - y;    }}// Contextpublic class Calculator {    private Operation operation;    public Calculator(Operation operation) {        this.operation = operation;    }    public void setOperation(Operation operation) {        this.operation = operation;    }    public int executeOperation(int x, int y) {        return operation.doOperation(x, y);    }}public class StrategyTest {    public static void main(String[] args) {        Calculator calculator = new Calculator(new OperationAdd());        System.out.println(calculator.executeOperation(1000, 24));        calculator.setOperation(new OperationMultiply());        System.out.println(calculator.executeOperation(1000, 24));    }}

角色:
1. Context(环境类):
环境类是使用算法的角色,它在解决某个问题(即实现某个方法)时可以采用多种策略。在环境类中维持一个对抽象策略类的引用实例,用于定义所采用的策略。

  1. Strategy(抽象策略类):
    它为所支持的算法声明了抽象方法,是所有策略类的父类,它可以是抽象类或具体类,也可以是接口。
    环境类通过抽象策略类中声明的方法在运行时调用具体策略类中实现的算法。
      
  2.  ConcreteStrategy(具体策略类):
    它实现了在抽象策略类中声明的算法,在运行时,具体策略类将覆盖在环境类中定义的抽象策略类对象,使用一种具体的算法实现某个业务处理。

    • 策略模式解析
      策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相通的工作,
      只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类和使用算法类之间的耦合。
      策略模式就是用来封装算法的,但是实践中,我们发现可以用它来分装几乎任何类型的规则,
      只要在分析过程中听到需要在不同的时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
0 0