MyBatis框架迭代器模式實(shí)現(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.'); }}
實(shí)現(xiàn) Iterator 接口就很方便的弄出一個迭代器,然后就可以使用hasNext和next方法了。
業(yè)務(wù)邏輯咱們不用管,只需要知道在調(diào)用next方法時,new了一個 PropertyTokenizer 實(shí)例, 而這個實(shí)例有個 children屬性, hasNext方法就是通過判斷這個children屬性是否為空來作為結(jié)束迭代的判斷條件。
具體的實(shí)現(xiàn)的我們不管,只需要領(lǐng)悟兩點(diǎn): 1. next需要干啥; 2. hasNext的如何判斷?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. SQL2000管理SQL7服務(wù)器出現(xiàn)TIMEOUT問題的解決2. Mysql入門系列:MYSQL圖像數(shù)據(jù)的處理3. SQLite教程(六):表達(dá)式詳解4. Mysql入門系列:建立MYSQL客戶機(jī)程序的一般過程5. Oracle數(shù)據(jù)庫刪除表中重復(fù)記錄的常見方法6. MySQL/MariaDB中如何支持全部的Unicode7. 導(dǎo)出錯誤編碼的mysql數(shù)據(jù)庫8. SQLite3 API 編程手冊9. Mysql入門系列:對MYSQL查詢中有疑問的數(shù)據(jù)進(jìn)行編碼10. mysql啟動時報(bào)錯 ERROR! Manager of pid-file quit without
