《研磨设计模式》chap14 迭代器模式(3) 举例
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap14 迭代器模式(3) 举例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. java的iterator
public class ArrayIteratorImpl implements Iterator{//用來(lái)存放被迭代的數(shù)組 private PayModel[] pms = null;//用來(lái)記錄當(dāng)前迭代到的位置索引 private int index = 0; public ArrayIteratorImpl(SalaryManager aggregate){ Collection<PayModel> tempCol = new ArrayList<PayModel>();for(PayModel pm : aggregate.getPays()){if(pm.getPay() < 3000){tempCol.add(pm);}}//然后把符合要求的數(shù)據(jù)存放到用來(lái)迭代的數(shù)組this.pms = new PayModel[tempCol.size()];int i=0;for(PayModel pm : tempCol){this.pms[i] = pm;i++;}}public class PayManager extends Aggregate{private List<PayModel> list = new ArrayList<PayModel>();//獲取工資列表 public List<PayModel> getPayList(){return list;}//計(jì)算工資 public void calcPay(){ PayModel pm1 = new PayModel();pm1.setPay(3800);pm1.setUserName("張三"); list.add(pm1); }public Iterator createIterator() {return list.iterator();} }2. 雙向迭代
public class ArrayIteratorImpl implements Iterator{public void previous(){if(index > 0 ){index = index - 1;}}3. 數(shù)據(jù)翻頁(yè)
public class ArrayIteratorImpl implements AggregationIterator{public Collection next(int num) {Collection col = new ArrayList();int count=0;while(hasNext() && count<num){col.add(pms[index]);//每取走一個(gè)值,就把已訪問(wèn)索引加1index++;count++;}return col;} public Collection previous(int num){Collection col = new ArrayList();int count=0;//簡(jiǎn)單的實(shí)現(xiàn)就是把索引退回去num個(gè),然后再取值。//但事實(shí)上這種實(shí)現(xiàn)是有可能多退回去數(shù)據(jù)的,比如:已經(jīng)到了最后一頁(yè),//而且最后一頁(yè)的數(shù)據(jù)不夠一頁(yè)的數(shù)據(jù),那么退回去num個(gè)索引就退多了 index = index - num;while(hasPrevious() && count<num){col.add(pms[index]);index ++;count++;}return col;}總結(jié)
以上是生活随笔為你收集整理的《研磨设计模式》chap14 迭代器模式(3) 举例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 《研磨设计模式》chap14 迭代器模式
- 下一篇: 《研磨设计模式》chap13 命令模式