MyBatis框架迭代器模式實現(xiàn)原理解析
迭代器模式,一直沒用過,也不會用。恰巧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屬性建立前后兩次迭代的關(guān)系 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.'); }}
實現(xiàn) Iterator 接口就很方便的弄出一個迭代器,然后就可以使用hasNext和next方法了。
業(yè)務(wù)邏輯咱們不用管,只需要知道在調(diào)用next方法時,new了一個 PropertyTokenizer 實例, 而這個實例有個 children屬性, hasNext方法就是通過判斷這個children屬性是否為空來作為結(jié)束迭代的判斷條件。
具體的實現(xiàn)的我們不管,只需要領(lǐng)悟兩點: 1. next需要干啥; 2. hasNext的如何判斷?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. golang實現(xiàn)mysql數(shù)據(jù)庫事務(wù)的提交與回滾2. MyBatis如何實現(xiàn)流式查詢的示例代碼3. Mybatis Limit實現(xiàn)分頁功能4. mybatis plus動態(tài)數(shù)據(jù)源切換及查詢過程淺析5. 解決db2事務(wù)日志已滿及日志磁盤空間已滿問題辦法詳解6. SQLite教程(二):C/C++接口簡介7. MyBatis SELECT基本查詢實現(xiàn)方法詳解8. 基于mysql的論壇(3)9. Mybatis在sqlite中無法讀寫byte[]類問題的解決辦法10. Mybatis分頁PageHelper插件代碼實例
