《研磨设计模式》chap14 迭代器模式(3) 举例
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap14 迭代器模式(3) 举例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. java的iterator
public class ArrayIteratorImpl implements Iterator{//用來存放被迭代的數組 private PayModel[] pms = null;//用來記錄當前迭代到的位置索引 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);}}//然后把符合要求的數據存放到用來迭代的數組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;}//計算工資 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. 數據翻頁
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]);//每取走一個值,就把已訪問索引加1index++;count++;}return col;} public Collection previous(int num){Collection col = new ArrayList();int count=0;//簡單的實現就是把索引退回去num個,然后再取值。//但事實上這種實現是有可能多退回去數據的,比如:已經到了最后一頁,//而且最后一頁的數據不夠一頁的數據,那么退回去num個索引就退多了 index = index - num;while(hasPrevious() && count<num){col.add(pms[index]);index ++;count++;}return col;}總結
以上是生活随笔為你收集整理的《研磨设计模式》chap14 迭代器模式(3) 举例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《研磨设计模式》chap14 迭代器模式
- 下一篇: 《研磨设计模式》chap13 命令模式