迭代器模式提供了顺序访问集合对象中的各种元素,而不暴露该对象内部结构的方法。如Java中遍历HashMap。
迭代器模式将遍历集合中所有元素的操作封装成迭代器类,其目的是在不暴露集合对象内部结构的情况下,对外提供统一访问集合的内部数据的方法。迭代器的实现一般包括一个迭代器,用于执行具体的遍历操作;一个Collection,用于存储具体的数据。Collection集合的迭代器UML设计图:
1)Collection接口:
package cn.jaa.iterator_pattern;/*** @Author: Jaa* @Description:* @Date 2023/12/5 23:02*/
public interface Collection {// 对集合元素的迭代public Iterator iterator();// 获取集合元素public Object get(int i);// 向添加元素public boolean add(Object obj);// 获取集合的大小public int size();
}
2)Collection接口实现类ListCollection:
package cn.jaa.iterator_pattern;import java.util.ArrayList;
import java.util.List;/*** @Author: Jaa* @Description: Collection接口实现类ListCollection* @Date 2023/12/5 23:07*/
public class ListCollection implements Collection {public List list = new ArrayList();@Overridepublic Iterator iterator() {return new ConcreteIterator(this);}@Overridepublic Object get(int i) {return list.get(i);}@Overridepublic boolean add(Object obj) {list.add(obj);return true;}@Overridepublic int size() {return list.size();}
}
3)迭代器接口Iterator:
package cn.jaa.iterator_pattern;/*** @Author: Jaa* @Description:* @Date 2023/12/5 23:08*/
public interface Iterator {// 前移指针public Object previous();// 后移指针public Object next();public boolean hasNext();
}
4)Iterator的实现类ConcreteIterator:
package cn.jaa.iterator_pattern;/*** @Author: Jaa* @Description: Iterator的实现类ConcreteIterator* @Date 2023/12/5 23:10*/
public class ConcreteIterator implements Iterator {private Collection collection;// 当前迭代器遍历到的元素位置private int pos = -1;public ConcreteIterator(Collection collection) {this.collection = collection;}@Overridepublic Object previous() {if (pos > 0) {pos--;}return collection.get(pos);}@Overridepublic Object next() {if (pos < collection.size() - 1) {pos++;}return collection.get(pos);}@Overridepublic boolean hasNext() {if (pos < collection.size() - 1) {return true;} else {return false;}}
}
5)测试迭代器模式:
package cn.jaa.iterator_pattern;import lombok.extern.slf4j.Slf4j;/*** @Author: Jaa* @Description:* @Date 2023/12/5 23:19*/
@Slf4j
public class IteratorDemoTest {public static void main(String[] args) {Collection collection = new ListCollection();collection.add("obj1");collection.add("obj2");collection.add("obj3");Iterator it = collection.iterator();while (it.hasNext()) {log.info((String) it.next());}}
}
打印结果: