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的如何判斷?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Mysql故障排除:Starting MySQL. ERROR! Manager of pid-file quit without updating file2. MySQL插入數據時,如果記錄不存在則insert,如果存在則update3. oracle觸發器介紹4. Mysql入門系列:建立MYSQL客戶機程序的一般過程5. 巧用SQL語言在ACCESS數據庫中批量替換內容6. Mysql入門系列:在MYSQL結果集上執行計算7. MySQL創始人發郵件尋求中國幫助8. MySQL存儲引擎選擇InnoDB還是MyISAM9. 學好Oracle的六條總結10. MYSQL技巧:為現有字段添加自增屬性

網公網安備