当前位置:网站首页>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
边栏推荐
- From zero to one, I will teach you to build a "search by text and map" search service (I)
- Nuxt - 每个页面单独设置 SEO 相关标签及网页标题、图标等(页面配置 head)
- pytorch 读写文件
- [C language] explain the thread exit function pthread_ exit
- PostgreSQL has a cross database references are not implemented bug
- Libuv库概述及libevent、libev、libuv对比(转载)
- ECS 四 Sync Point、Write Group、Version Number
- Anaconda's own Spyder editor starts with an error
- mysql动态加表只能加小表,加大表跑着跑着任务就不读数据了,有什么解决办法吗
- Canoe- how to parse messages and display information in the trace window (use of program node and structure type system variables)
猜你喜欢
![[C language] explain the thread exit function pthread_ exit](/img/fb/96db1c712370dbb216a06440ecdc5e.png)
[C language] explain the thread exit function pthread_ exit

SQL two columns become multi row filter display

New listing of operation light 3.0 -- a sincere work of self subversion across the times

树莓派用VNC Viewer方式远程连接

What is the method of connection query in MySQL

Multi machine LAN office artifact rustdesk use push!!!

1018 锤子剪刀布

Five thousand years of China

干货丨微服务架构是什么?有哪些优点和不足?

Hcie security day41: theoretical learning: information collection and network detection
随机推荐
1017 a divided by B
Remediation for Unsafe Cryptographic Encryption
Seattention channel attention mechanism
sink端 一般都是jdbc的insert update delete么?
为什么说测试岗位是巨坑?8年测试人告诉你千万别上当
Error accessing database
If you choose the right school, you can enter Huawei as a junior college. I wish I had known
LabVIEW displays Unicode characters
[C language] explain the thread recycling function pthread_ join
[new function] ambire wallet integrates Metis network
请问大佬,Oracle CDC报错 Call snapshotState on closed sou
Untitled
Hcie security day41: theoretical learning: information collection and network detection
Emotional changes need to be controlled
Remediation for Unsafe Cryptographic Encryption
Is the increased life insurance off the shelf? What additional life insurance products are available now?
Rapid development project -vscode plug-in
What is the dry goods microservice architecture? What are the advantages and disadvantages?
ROS TF coordinate transformation Library & rewrite to create high frequency coordinate transformation broadcaster
Cucumber test practice