当前位置:网站首页>Iterator pattern
Iterator pattern
2022-06-29 04:23:00 【Change with affection】
Iterator pattern (Iterator Pattern)
yes Java and .Net Very common design patterns in programming environments . This pattern is used to sequentially access the elements of a collection object , You do not need to know the underlying representation of the collection object .
The iterator pattern is a behavioral pattern .
If our set elements are implemented in different ways , There are arrays , also java Set class of , Or there are other ways , When the client wants to traverse these collection elements, it needs to use a variety of traversal methods , It also exposes the internal structure of the elements , Consider using the iterator pattern to solve . Provides a unified interface for traversing collection elements , Traversing set elements in a consistent way , You do not need to know the underlying representation of the collection object , namely : Do not expose its internal structure ..
Case study
Show the composition of the school department in a page , There are many colleges in a school , A college has many departments .
public class Department {
private String name;
private String desc;
public Department(String name, String desc) {
super();
this.name = name;
this.desc = desc;
}
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public String getDesc() {
return desc; }
public void setDesc(String desc) {
this.desc = desc; }
}
public class ComputerCollegeIterator implements Iterator {
// Here we need Department How to store => Array
Department[] departments;
int position = 0; // The location of traversal
public ComputerCollegeIterator(Department[] departments) {
this.departments = departments; }
// Determine if there is another element
@Override
public boolean hasNext() {
if(position >= departments.length || departments[position] == null) {
return false;
}else {
return true;
}
}
@Override
public Object next() {
Department department = departments[position];
position += 1;
return department;
}
// Delete method , Default empty implementation
public void remove() {
}
}
public class InfoColleageIterator implements Iterator {
List<Department> departmentList; // The school of information engineering is based on List Storage system
int index = -1;// Indexes
public InfoColleageIterator(List<Department> departmentList) {
this.departmentList = departmentList; }
// Judge list Is there another element in
@Override
public boolean hasNext() {
if(index >= departmentList.size() - 1) {
return false;
} else {
index += 1;
return true;
}
}
@Override
public Object next() {
return departmentList.get(index);
}
// Empty implementation remove
public void remove() {
}
}
public interface College {
public String getName();
// The way to add a department
public void addDepartment(String name, String desc);
// Returns an iterator , Traverse
public Iterator createIterator();
}
public class ComputerCollege implements College {
Department[] departments;
int numOfDepartment = 0 ;// Saves the number of objects in the current array
public ComputerCollege() {
departments = new Department[5];
addDepartment("Java major ", " Java major ");
addDepartment("PHP major ", " PHP major ");
addDepartment(" Big data ", " Big data ");
}
@Override
public String getName() {
return " school of computing "; }
@Override
public void addDepartment(String name, String desc) {
Department department = new Department(name, desc);
departments[numOfDepartment] = department;
numOfDepartment += 1;
}
@Override
public Iterator createIterator() {
return new ComputerCollegeIterator(departments);
}
}
public class InfoCollege implements College {
List<Department> departmentList;
public InfoCollege() {
departmentList = new ArrayList<Department>();
addDepartment(" Information security ", " Information security ");
addDepartment(" Network security ", " Network security ");
addDepartment(" Server security professional ", " Server security professional ");
}
@Override
public String getName() {
return " School of Information Engineering "; }
@Override
public void addDepartment(String name, String desc) {
Department department = new Department(name, desc);
departmentList.add(department);
}
@Override
public Iterator createIterator() {
return new InfoColleageIterator(departmentList); }
}
public class OutPutImpl {
// College assembly
List<College> collegeList;
public OutPutImpl(List<College> collegeList) {
this.collegeList = collegeList;
}
// Traverse all colleges , And then call printDepartment Output Department of each college
public void printCollege() {
// from collegeList Take out all the Colleges , Java Medium List Already realized Iterator
Iterator<College> iterator = collegeList.iterator();
while(iterator.hasNext()) {
// Take out a college
College college = iterator.next();
System.out.println("=== "+college.getName() +"=====" );
printDepartment(college.createIterator()); // Get the corresponding iterator
}
}
// Output College output system
public void printDepartment(Iterator iterator) {
while(iterator.hasNext()) {
Department d = (Department)iterator.next();
System.out.println(d.getName());
}
}
}
public class Client {
public static void main(String[] args) {
// Create a college
List<College> collegeList = new ArrayList<College>();
ComputerCollege computerCollege = new ComputerCollege();
InfoCollege infoCollege = new InfoCollege();
collegeList.add(computerCollege);
//collegeList.add(infoCollege);
OutPutImpl outPutImpl = new OutPutImpl(collegeList);
outPutImpl.printCollege();
}
}
The iterator pattern is JDK-ArrayList Source code analysis of aggregate application
public class IteratorDemo {
public static void main(String[] args) {
List<String> a = new ArrayList<>();
a.add("jack");// ..
// Get iterator
Iterator Itr = a.iterator();
while (Itr.hasNext()) {
System.out.println(Itr.next());
}
}
}

ArrayList Aggregate implementation class , Implements the aggregation interface List
public interface List<E> extends Collection<E> {
Iterator<E> iterator();
}
Inner class Itr Realized Iterator Interface , Is a concrete interface implementation class .
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
public Iterator<E> iterator() {
return new Itr();
}
/** * An optimized version of AbstractList.Itr */
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}
- Inner class Itr Act as a concrete implementation iterator Iterator Class , As ArrayList Inner class
- List It acts as an aggregation interface , Contains a iterator() Method , Returns an iterator object
- ArrayList It's about implementing the aggregation interface List Subclasses of , Realized iterator()
- Iterator The interface system provides
- The iterator pattern solves different sets (ArrayList ,LinkedList) Unified Ergodic problem
summary
advantage
- Provides a unified method to traverse objects , Customers don't have to think about the type of aggregation anymore , One way to traverse an object
- Hides the internal structure of the aggregation , When the client wants to traverse the aggregation, it can only get the iterator , Without knowing the specific composition of the polymerization
- Provides a design idea , Is that a class should have only one reason for change ( It's called the single responsibility principle ). In an aggregate class , Let's separate iterators , It is to separate the responsibility of managing the object collection from that of traversing the object collection , In this way, if the assembly changes , Only aggregate objects... Are affected . And if the traversal changes , Only iterators are affected .
- When you want to show a group of similar objects , Or when traversing the same set of objects , It's good to use iterator mode
shortcoming
- Every aggregate object has to - An iterator , It will generate multiple iterator bad management classes
边栏推荐
- 如何创建 robots.txt 文件?
- My creation anniversary
- NotImplementedError: Could not run torchvision::nms
- Webapck system foundation
- Remediation for Unsafe Cryptographic Encryption
- Seattention channel attention mechanism
- The five levels of making money, which level are you on?
- 1015 theory of virtue and talent
- 科班出身,结果外包都不要
- Blue Bridge Cup ruler method
猜你喜欢

Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform

SEAttention 通道注意力机制

I came from a major, so I didn't want to outsource

快速开发项目-VScode插件

iNFTnews | 元宇宙技术将带来全新的购物体验

IDEA修改jvm内存

Implementation of thread pool based on variable parameter template

【新功能】Ambire 钱包集成了 Metis 网络

Hcie security day41: theoretical learning: information collection and network detection

Here comes Wi Fi 7. How strong is it?
随机推荐
Here comes Wi Fi 7. How strong is it?
Hot renewal process
Remediation for Unsafe Cryptographic Encryption
SEAttention 通道注意力机制
Using assetstudio/unitystudio uabe, etc
Cucumber test practice
直播预约|AWS Data Everywhere 系列活动
From zero to one, I will teach you to build a "search by text and map" search service (I)
不使用union实现Mysql 列转行
String不同创建方式的区别
On June 27, 2022, I have the right to choose the journey of the summer vacation.
MySQL subquery
Emotional changes need to be controlled
[WC2021] 斐波那契——数论、斐波那契数列
SQL two columns become multi row filter display
[new function] ambire wallet integrates Metis network
Binary tree serialization and deserialization (leetcode (difficult))
Build a simple website by yourself
iNFTnews | 元宇宙技术将带来全新的购物体验
女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了