• 【行为型】策略模式


    一、策略模式

    定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。

    策略定义:

    public interface Strategy {
      void algorithmInterface();
    }
    
    public class ConcreteStrategyA implements Strategy {
      @Override
      public void  algorithmInterface() {
        //具体的算法...
      }
    }
    
    public class ConcreteStrategyB implements Strategy {
      @Override
      public void  algorithmInterface() {
        //具体的算法...
      }
    }

    策略创建:为了封装创建逻辑,我们需要对客户端代码屏蔽创建细节。我们可以把根据type创建策略的逻辑抽离出来,放到工厂类中。

    针对无状态的策略:使用Map

     1 public class StrategyFactory {
     2   private static final Map<String, Strategy> strategies = new HashMap<>();
     3 
     4   static {
     5     strategies.put("A", new ConcreteStrategyA());
     6     strategies.put("B", new ConcreteStrategyB());
     7   }
     8 
     9   public static Strategy getStrategy(String type) {
    10     if (type == null || type.isEmpty()) {
    11       throw new IllegalArgumentException("type should not be empty.");
    12     }
    13     return strategies.get(type);
    14   }
    15 }
    View Code

    针对有状态的策略:

     1 public class StrategyFactory {
     2   public static Strategy getStrategy(String type) {
     3     if (type == null || type.isEmpty()) {
     4       throw new IllegalArgumentException("type should not be empty.");
     5     }
     6 
     7     if (type.equals("A")) {
     8       return new ConcreteStrategyA();
     9     } else if (type.equals("B")) {
    10       return new ConcreteStrategyB();
    11     }
    12 
    13     return null;
    14   }
    15 }
    View Code

    策略模式使用:

    1、配置文件指定策略名,然后通过工厂在动态时决定  

    2、直接代码指定具体策略


     

    二、职责链模式

    典型实现:Servlet的filter chain(addFilter、doFilter)、Spring Interceptor


    三、状态模式(不常用,适用状态机)

    状态模式一般用来实现状态机,而状态机常用在游戏、工作流引擎等系统开发中。不过,状态机的实现方式有多种,除了状态模式,比较常用的还有分支逻辑法和查表法。

  • 相关阅读:
    Google和百度、雅虎的站内搜索代码
    Unidac:解决“trying to modify readonly Field”问题!
    如何通过BDE连接一个非1433端口的SQL SERVER
    工作总结
    iOS开发肯定会遇到的
    自定义delegate和系统定义dalegate的区别
    C语言中关于字符串左右循环移位的问题
    iphone 文件保存策略
    iphone学习各种资源
    IOS开发系列之阿堂教程:tableView的下拉涮新功能实践
  • 原文地址:https://www.cnblogs.com/clarino/p/15720956.html
Copyright © 2020-2023  润新知