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的如何判斷?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: