zoukankan      html  css  js  c++  java
  • MyBatis框架之迭代器模式

    迭代器模式,一直没用过,也不会用。恰巧MyBatis框架中也使用到了迭代器模式,而且看起来还比较简单,在以后的工作中,若有需要咱们可模仿它的套路来干。

    直接上代码

    import java.util.Iterator;
    
    /**
     * @author Clinton Begin
     */
    public class PropertyTokenizer implements Iterator<PropertyTokenizer> {
      private String name;
      private final String indexedName;
      private String index;
      private final String children;  // 通过这个children属性建立前后两次迭代的关系
    
      public PropertyTokenizer(String fullname) {
        int delim = fullname.indexOf('.');
        if (delim > -1) {
          name = fullname.substring(0, delim);
          children = fullname.substring(delim + 1);
        } else {
          name = fullname;
          children = null;
        }
        indexedName = name;
        delim = name.indexOf('[');
        if (delim > -1) {
          index = name.substring(delim + 1, name.length() - 1);
          name = name.substring(0, delim);
        }
      }
    
      public String getName() {
        return name;
      }
    
      public String getIndex() {
        return index;
      }
    
      public String getIndexedName() {
        return indexedName;
      }
    
      public String getChildren() {
        return children;
      }
    
      @Override
      public boolean hasNext() {
        return children != null;
      }
    
      @Override
      public PropertyTokenizer next() {
        return new PropertyTokenizer(children);
      }
    
      @Override
      public void remove() {
        throw new UnsupportedOperationException("Remove is not supported, as it has no meaning in the context of properties.");
      }
    }

    实现 Iterator 接口就很方便的弄出一个迭代器,然后就可以使用hasNext和next方法了。

    业务逻辑咱们不用管,只需要知道在调用next方法时,new了一个 PropertyTokenizer 实例, 而这个实例有个 children属性, hasNext方法就是通过判断这个children属性是否为空来作为结束迭代的判断条件。

    具体的实现的我们不管,只需要领悟两点: 1. next需要干啥; 2. hasNext的如何判断?

  • 相关阅读:
    从输入URL到页面加载发生了什么
    JS常用操作方法图表
    前端面试技巧与技术栈准备梳理
    ES6学习笔记(二)—— 通过ES6 Module看import和require区别
    我所理解的event loop
    在npm上发布一个自己的包
    微信小程序--登录流程梳理
    CSS3动画和JS动画的比较
    基于Inception搭建MySQL SQL审核平台Yearing
    MySQL数据库主从切换脚本自动化
  • 原文地址:https://www.cnblogs.com/z-qinfeng/p/12216021.html
Copyright © 2011-2022 走看看