迭代器模式
迭代器(Iterator)模式:提供一个对象(迭代器)来顺序访问聚合对象(迭代数据)中的一系列数据,而不暴露聚合对象的内部表示。
现实开发中,我们几乎无需编写迭代器,基本数据结构链表、树、图的迭代器已经都有了。除非要重写迭代逻辑
案例
public abstract class BeautifulMan {//不方便暴露给外界的集合。只允许外界获取而不可以操作private List<String> girlFriends = new ArrayList<>();void likeYou(String name){girlFriends.add(name);};void sayBye(String name){girlFriends.remove(name);};/*** 获取迭代器* @return*/public Itr getIterator(){return new Iterator();}/*** 具体迭代器*/class Iterator implements Itr{private int cursor = 0; //当前指针public boolean hasNext(){return cursor < girlFriends.size();}public String next(){//第一次调用返回第一个数据//下一次再调用自动访问下一个数据String s = girlFriends.get(cursor);cursor++;return s;}@Overridepublic String firstLove() {return girlFriends.get(0);}@Overridepublic String current() {return girlFriends.get(girlFriends.size()-1);}}/*** 抽象迭代器,写在外部该怎么写?*/interface Itr {//有没有下一个boolean hasNext();//返回下一个String next();//返回初恋(第一个)String firstLove();//返回现任(最后一个女朋友)String current();}}
测试:
public class MainTest {public static void main(String[] args) {MaYuCheng cheng = new MaYuCheng();cheng.likeYou("王刚");cheng.likeYou("李强");cheng.likeYou("赵根");BeautifulMan.Itr itr = cheng.getIterator();String s = itr.firstLove();System.out.println(s);String current = itr.current();System.out.println(current);System.out.println("=================");while (itr.hasNext()){String next = itr.next();System.out.println(next);}}
}