迭代器模式
迭代器简介:
顺序访问集合对象的元素,不需要知道集合对象的底层表示。
关键接口有:hasNext() 判断是否还有下一个元素, next() 下一个元素对象。
参与角色:
1)聚合类(容器类)接口
2)具体的容器类
3)Iterator接口
4)Iterator实现类
5)元素类
优点:
分离了集合对象的遍历行为。
缺点:
由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。
使用案例或场景:
使用场景:需要遍历聚合类
栗子:假设买彩票中了100万,成为土豪了,要给家人都全部换一步新手机,然后根据不同爱好买了慢慢一箱子的手机去给家里人发,有华为啊、小米啊、苹果啊等等,取出来哪个发哪个。
代码:
1、实体类:
//实体类 public class Phone { private String phoneName; public Phone(String phoneName){ this.phoneName = phoneName; } public String getPhoneName() { return phoneName; }
2、聚合接口:
/** * 聚合类接口 */ public interface PhoneAggregate { public void addPhone(Phone phone); public void removePhone(Phone phone); public PhoneIDerator getPhoneIderator(); }
3、Iterator接口:
//Iterator接口 public interface PhoneIDerator { public Phone hasNext(); public boolean next(); }
4、具体的容器类:
/** * 具体的容器类 */ public class PhoneAggregateImpl implements PhoneAggregate { List listPhone; public PhoneAggregateImpl(){ listPhone = new ArrayList(); } @Override public void addPhone(Phone phone) { listPhone.add(phone); } @Override public void removePhone(Phone phone) { listPhone.remove(phone); } @Override public PhoneIDerator getPhoneIderator() { return new PhoneIDeratorImpl(listPhone); } }
5、Iterator实现类:
/** * Iterator实现类 */ public class PhoneIDeratorImpl implements PhoneIDerator { List listPhone; int posion; Phone phone; public PhoneIDeratorImpl(List list) { this.listPhone = list; } @Override public Phone hasNext() { System.out.println("改元素的位置是:" + posion); phone = (Phone) listPhone.get(posion); posion++; return phone; } @Override public boolean next() { if (posion < listPhone.size()) { return false; } return true; } }
最后就是需要我们进行测试了:
public class Test { public static void main(String[] args) { Phone phone1 = new Phone("小米手机"); Phone phone2 = new Phone("OPPO手机"); Phone phone3 = new Phone("VIVO手机"); Phone phone4 = new Phone("荣耀手机"); Phone phone5 = new Phone("苹果手机"); PhoneAggregate aggregate = new PhoneAggregateImpl(); aggregate.addPhone(phone1); aggregate.addPhone(phone2); aggregate.addPhone(phone3); aggregate.addPhone(phone4); aggregate.addPhone(phone5); System.out.println("----------手机列表----------"); Idertor(aggregate); System.out.println("----------删除后的手机列表----------"); aggregate.removePhone(phone2); aggregate.removePhone(phone3); Idertor(aggregate); } public static void Idertor(PhoneAggregate aggregate){ PhoneIDerator phoneIderator = aggregate.getPhoneIderator(); while (!phoneIderator.next()){ Phone phone = phoneIderator.hasNext(); System.out.println("该手机为:"+phone.getPhoneName()); } } }
输出结果:
迭代器在源码中的应用:
java.util.Iterator
想要飞得更高,就该忘记地平线!