大话设计模式——读书笔记9策略模式

: 大话设计模式–读书笔记策略模式

策略模式

策略模式:定义了算法族,分别封装,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户

结构图

这里写图片描述

商场收银时,如何促销,使用打折还是返利,其实都是一种算法,(算法本身是一种策略),最重要的是这些算法是随时都可能相互替换的,者就是变化点。封装变化点是面向对象的一种很重要的思想方式。

Strategy类 :定义所有支持的算法的公共接口

abstract class Strategy{
    //算法方法
    public abstract void AlgorithmInterface();
}

ConcreteStrateyA:封装了具体的算法或者行为,继承于Strategy

class ConcreteStrateyA implements Strategy{
  //算法A实现方法
  public void AlgorithmInterface(){
    System.out.println("算法A实现");
  }
}

ConcreteStrateyB:封装了具体的算法或者行为,继承于Strategy

class ConcreteStrateyB implements Strategy{
  //算法B实现方法
  public void AlgorithmInterface(){
    System.out.println("算法B实现");
  }
}

ConcreteStrateyC:封装了具体的算法或者行为,继承于Strategy

class ConcreteStrateyC implements Strategy{
  //算法C实现方法
  public void AlgorithmInterface(){
    System.out.println("算法B实现");
  }
}

Context: 用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用

class Context{
  Strategy strategy;
  public Context(Strategy strategy){
    this.strategy = strategy;
  }

  //上下文接口
  public void ContextInterface(){
    strategy.AlgorithmInterface();
  }
}

客户端代码:

public static void main(String[] args){
  Context context;
  context = new Context(new ConcreteStategyA());
  context.ContextInterface();

  context = new Context(new ConcreteStategyB());
  context.ContextInterface();

  context = new Context(new ConcreteStategyC());
  context.ContextInterface();

}

策略模式解析:

策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,他可以以相同的方式定义调用所有的算法,减少了各种算法类之间的耦合

优点:
1.策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或者行为。继承有助于析取出这些算法的公 共功能。
2.策略算法模式的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
3.策略就是用来封装算法,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间引用不同的业务规则,就可以使用策略模式处理这种变化的可能性

(抽象工程模式章节—反射简介)

反射模式写过了,但是需要的时候还是再看看吧。感觉也需要重新学习了。

猜你喜欢

转载自blog.csdn.net/u010887126/article/details/80160043
今日推荐