当前位置:网站首页>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
边栏推荐
- MySQL column to row conversion without Union
- What is the method of connection query in MySQL
- Implementation of thread pool based on variable parameter template
- 使用AssetStudio/UnityStudio UABE等
- Idea modifying JVM memory
- How to quickly install MySQL 5.7.17 under CentOS 6.5
- The five levels of making money, which level are you on?
- Build a simple website by yourself
- 请问大佬,Oracle CDC报错 Call snapshotState on closed sou
- Practical part: solving the function conflict between swagger and user-defined parameter parser
猜你喜欢

JDBC learning

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

SQL two columns become multi row filter display

ROS TF coordinate transformation Library & rewrite to create high frequency coordinate transformation broadcaster

快速开发项目-VScode插件

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

Daily practice - February 15, 2022

Untitled

Redis cache penetration, cache breakdown, cache avalanche

SEAttention 通道注意力機制
随机推荐
[wc2021] Fibonacci - number theory, Fibonacci sequence
What are the circular statements of MySQL
[C language] explain the thread exit function pthread_ exit
Has my future been considered in the cloud native development route?
Analysis on the types of source code anti leakage technology
Seattention channel attention mechanism
请问大佬,Oracle CDC报错 Call snapshotState on closed sou
Ansible最佳实践之Playbook不同上下文提权Demo
JDBC man Han building code
人民银行印发《关于支持外贸新业态跨境人民币结算的通知》
热更新流程
How to display all MySQL databases
New listing of operation light 3.0 -- a sincere work of self subversion across the times
Go Foundation (I)
On June 27, 2022, I have the right to choose the journey of the summer vacation.
Live broadcast appointment AWS data everywhere series activities
What is the method of connection query in MySQL
If you choose the right school, you can enter Huawei as a junior college. I wish I had known
【HackTheBox】dancing(SMB)
Nuxt - set SEO related tags, page titles, icons, etc. separately for each page (page configuration head)