MyBatis框架迭代器模式實(shí)現(xiàn)原理解析
迭代器模式,一直沒用過,也不會(huì)用。恰巧MyBatis框架中也使用到了迭代器模式,而且看起來還比較簡(jiǎn)單,在以后的工作中,若有需要咱們可模仿它的套路來干。
直接上代碼
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; // 通過這個(gè)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 接口就很方便的弄出一個(gè)迭代器,然后就可以使用hasNext和next方法了。
業(yè)務(wù)邏輯咱們不用管,只需要知道在調(diào)用next方法時(shí),new了一個(gè) PropertyTokenizer 實(shí)例, 而這個(gè)實(shí)例有個(gè) children屬性, hasNext方法就是通過判斷這個(gè)children屬性是否為空來作為結(jié)束迭代的判斷條件。
具體的實(shí)現(xiàn)的我們不管,只需要領(lǐng)悟兩點(diǎn): 1. next需要干啥; 2. hasNext的如何判斷?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 上海Oracle OpenWorld大會(huì)紀(jì)事-07.192. DB2編程序小小技巧3. MySQL分區(qū)的優(yōu)點(diǎn)4. 解決Oracle賬戶被鎖定的問題5. Oracle9i(9.2.0.4) Installation Errors Under Redhat 96. sql server注冊(cè)表操作相關(guān)的幾個(gè)未公開過程7. 自己動(dòng)手把ACCESS轉(zhuǎn)換到SQLSERVER的方法8. 關(guān)于oracle日期函數(shù)的介紹和使用9. 通過實(shí)例解析MySql CURRENT_TIMESTAMP函數(shù)10. 如何安裝MySQL 壓縮包
