温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis框架迭代器模式实现原理解析

发布时间:2020-10-13 23:08:15 来源:脚本之家 阅读:157 作者:我太难了008 栏目:编程语言

迭代器模式,一直没用过,也不会用。恰巧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的如何判断?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI