《研磨设计模式》chap14 迭代器模式(1)简介
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap14 迭代器模式(1)简介
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public abstract class Aggregate { public abstract Iterator createIterator();
}public class ConcreteAggregate extends Aggregate { private String[] ss = null;//示意,表示聚合對象具體的內容 public ConcreteAggregate(String[] ss){this.ss = ss;} public Iterator createIterator() {//實現創建Iterator的工廠方法return new ConcreteIterator(this);}public Object get(int index){Object retObj = null;if(index < ss.length){retObj = ss[index];}return retObj;}public int size(){return this.ss.length;}
}public interface Iterator { public void first(); public void next(); public boolean isDone(); public Object currentItem();
}public class ConcreteIterator implements Iterator { private ConcreteAggregate aggregate; private int index = -1; public ConcreteIterator(ConcreteAggregate aggregate) {this.aggregate = aggregate;} public void first(){index = 0;}public void next(){if(index < this.aggregate.size()){index = index + 1;}}public boolean isDone(){if(index == this.aggregate.size()){return true;}return false;}public Object currentItem(){return this.aggregate.get(index);}
}client:String[] names = {"張三","李四","王五"};//創建聚合對象Aggregate aggregate = new ConcreteAggregate(names);//循環輸出聚合對象中的值Iterator it = aggregate.createIterator();//首先設置迭代器到第一個元素it.first();while(!it.isDone()){//取出當前的元素來Object obj = it.currentItem();System.out.println("the obj=="+obj);//如果還沒有迭代到最后,那么就向下迭代一個it.next();}
總結
以上是生活随笔為你收集整理的《研磨设计模式》chap14 迭代器模式(1)简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《研磨设计模式》chap16 模板方法模
- 下一篇: 《研磨设计模式》chap14 迭代器模式