当前位置:网站首页>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
边栏推荐
- If I hadn't talked to Ali P7, I wouldn't know I was a mallet
- Anaconda's own Spyder editor starts with an error
- How sqlserver queries and removes results with null fields in the whole column
- 项目开发修养
- Redis 缓存穿透、缓存击穿、缓存雪崩
- Using assetstudio/unitystudio uabe, etc
- 1017 A除以B分
- The last week! Summary of pre competition preparation for digital model American Games
- The 30th day of force deduction (DP topic)
- [C language] explain the thread recycling function pthread_ join
猜你喜欢

Why is the test post a giant pit? The 8-year-old tester told you not to be fooled

SQL two columns become multi row filter display

How sqlserver queries and removes results with null fields in the whole column

The 30th day of force deduction (DP topic)

Libuv library overview and comparison of libevent, libev and libuv (Reprint)

What are the MySQL database constraint types

如何创建 robots.txt 文件?

What are the basic usage methods of MySQL

从零到一,教你搭建「以文搜图」搜索服务(一)

不使用union实现Mysql 列转行
随机推荐
Using assetstudio/unitystudio uabe, etc
The great gods take connections from the MySQL connection pool in the open of the rich function. The initialization of the connection pool is 20. If the parallelism of the rich function is 1
MySQL subquery
【Laravel系列8】走出 Laravel 的世界
MySQL column to row conversion without Union
CDC2.2.1还不支持postgresql14.1么?基于pgbouncer连接方式下,以5433
Webassembly learning - dynamic linking
LabVIEW显示Unicode字符
热更新流程
How to quickly change the database name in MySQL
String不同创建方式的区别
Live broadcast appointment AWS data everywhere series activities
Is the increased life insurance off the shelf? What additional life insurance products are available now?
How to create robots Txt file?
If I hadn't talked to Ali P7, I wouldn't know I was a mallet
1017 A除以B分
干货丨微服务架构是什么?有哪些优点和不足?
[performance test] introduction and installation of JMeter
Redis 缓存穿透、缓存击穿、缓存雪崩
Actual combat! Another opening method of magic modified swagger and knife4j