迭代器模式(Iterator Pattern)
又称为游标模式(Cursor Pattern),它提供了一种顺序访问集合/容器对象元素的方法,而又无须暴露集合内部表示。
本质:抽离集合对象迭代行为到迭代器中,提供一致访问接口。
属于行为型模式。
代码:
public interface Iterator{ boolean hasNext(); E next(); }
public class ConcreteIterator implements Iterator{ private List list; private int cursor = 0; public ConcreteIterator(List list){ this.list = list; } public boolean hasNext(){ return this.cursor < this.list.size(); } public E next(){ return this.list.get(this.cursor ++); } }
public interface IAggregate{ boolean add(E element); boolean remove(E element); Iterator iterator(); }
public class ConcreteAggregate implements IAggregate{ private List list = new Arraylist(); public boolean add(E element){ return this.list.add(element); } public boolean remove(E element){ return this.list.remove(element); } public Iterator iterator(){ return new ConcreteIterator(this.list); } }
public class Test { public static void main(String[] args) { IAggregate aggregate = new ConcreteAggregate(); aggregate.add("java"); aggregate.add("python"); aggregate.add("javascript"); Iterator iterator = aggregate.iterator(); while(iterator.hasNext()){ String element = iterator.next(); System.out.println(element); } } }
输出结果:
java python javascript
上一篇:[大模型]GLM-4-9B-Chat WebDemo 部署
下一篇:微服务基础篇:MQ(MessageQueue)消息队列(同步异步通讯,RabbitMQ快速入门,SpringAMQP,简单队列模型,工作队列模型,发布订阅模型,消息转换器)