In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
这篇文章主要介绍"什么是迭代器模式",在日常操作中,相信很多人在什么是迭代器模式问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"什么是迭代器模式"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
迭代器模式:提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。
迭代器模式适用场景:
访问一个聚合对象的内容而无需暴露它的内部表示
支持对聚合对象的多种遍历
为遍历不同的聚合结构提供一个统一的接口
迭代器模式组件:
Aggregate(聚合-抽象容器角色):定义集合并负责创建具体迭代器对象的接口
ConcreteAggregate(具体聚合-具体容器角色):实现抽象容器的具体实现类
Iterator(抽象迭代器角色):负责定义访问和遍历元素的接口
ConcreteIterator(具体迭代器角色):实现迭代器接口
迭代器模式组件实例:
抽象容器角色:
public class User { private String name; private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }}public interface Aggregate { Iterator iterator();}
具体容器角色:
import java.util.ArrayList;import java.util.List;public class ConcreteAggregate implements Aggregate { private List list = new ArrayList(); public ConcreteAggregate() { list.add(new User("luther0", 30)); list.add(new User("luther1", 31)); list.add(new User("luther2", 32)); list.add(new User("luther3", 33)); } @Override public Iterator iterator() { return new ConcreteIterator(list); }}
抽象迭代器角色:
public interface Iterator { boolean hasNext(); T next();}
具体迭代器角色:
import java.util.Arrays;import java.util.List;public class ConcreteIterator implements Iterator { private List userList; private int index; public ConcreteIterator(List userList) { this.userList = userList; } public ConcreteIterator(User[] users) { this.userList = Arrays.asList(users); } @Override public boolean hasNext() { return index < userList.size(); } @Override public User next() { return userList.get(index++); }}
客户端调用:
public class App { public static void main(String[] args) { Iterator iterator = new ConcreteAggregate().iterator(); while (iterator.hasNext()) { User next = iterator.next(); System.out.println(next.toString()); } }}
迭代器模式总结:
封装容器的内部实现细节,简化客户端的访问和获取容器内数据。
客户端可以通过相同的方式遍历不同的容器对象。
我们可以根据客户端需求让容器实现不同的迭代算法,从而可以用不同的遍历方式来访问容器数据。
增加了系统复杂度,但是便于扩展
到此,关于"什么是迭代器模式"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.