当前位置:网站首页>Iterator pattern of behavioral pattern
Iterator pattern of behavioral pattern
2022-07-25 23:57:00 【w ͏ l ͏ j ͏】
Iterator pattern
Why the iterator pattern appears ?
In programming , We often need to access various elements in the aggregate object , For example, the traversal of linked lists , Our usual practice is to put the creation and traversal of the linked list in a class , But this approach is not conducive to expansion , Modifying the traversal algorithm requires modifying the source code , It violates the open close principle . But if you let users implement traversal by themselves , It will not only expose the internal representation of the aggregate object , It will also increase the burden on users , To solve the above problems , There is Iterator pattern . The iterator pattern refers to inserting an iterator between the client access class and the aggregate class , This separates the aggregate object from its traversal , At the same time, it will not expose the internal details of the aggregate object .
What is iterator mode ?
Definition : Provides an object to sequentially access a series of data in an aggregate object , Without exposing the internal representation of the aggregate object . The iterator pattern is an object behavior pattern .
advantage :
- You can access the content of an aggregate object without exposing its internal representation .
- Support different traversal methods , Subclasses of iterators can be customized to implement new traversal methods .
- Observe the principle of single responsibility and the principle of opening and closing .
- Good encapsulation , It provides a unified interface for traversing different aggregation structures .
- There is little need for custom iterators in development , Open source framework provides API Generally enough .
The structure and implementation of patterns
The iterator pattern separates the traversal behavior of aggregate objects , Abstract to iterator class , The purpose is to... Without exposing the internal structure of the aggregate object , Let external code transparently access aggregated internal data .
structure
role
- Abstract aggregation (Aggregate) role : Define storage 、 add to 、 Delete aggregate objects and create interfaces for iterator objects .
- Concrete aggregation (ConcreteAggregate) role : Implement Abstract aggregation classes , Returns an instance of a concrete iterator .
- Abstract iterator (Iterator) role : Define interfaces to access and traverse aggregate elements , Usually contains hasNext()、first()、next() Other methods .
- Specific iterators (Concretelterator) role : Implement the methods defined in the abstract iterator interface , Complete the traversal of the aggregate object , Record the current position of the traversal .

Realization
Use the iterator to traverse the students in the classroom .
package com.pattern.Iterator;
/** * @author wlj * @Classname Aggregate * @Description Aggregate interface * @Date 7/25/2022 10:50 AM */
public interface Aggregate {
// Add aggregate objects
void addAggregate(Object obj);
// Delete aggregate object
void deleteAggregate(Object obj);
// Acquisition iterator
Iterator getIterator();
}
package com.pattern.Iterator;
import java.util.ArrayList;
/** * @author wlj * @Classname ConcreteAggregate * @Description Concrete aggregate objects (ConcreteAggregate) * @Date 7/25/2022 10:58 AM */
public class ConcreteAggregate implements Aggregate{
ArrayList<Object> arrayList = new ArrayList<Object>();
@Override
public void addAggregate(Object obj) {
arrayList.add(obj);
}
@Override
public void deleteAggregate(Object obj) {
arrayList.remove(obj);
}
@Override
public Iterator getIterator() {
return new ConcreteIterator(arrayList);
}
}
package com.pattern.Iterator;
/** * @author wlj * @Classname Iterator * @Description Iterator interface * @Date 7/25/2022 10:55 AM */
public interface Iterator {
// first
Object first();
// next
Object next();
// hasNext
boolean hasNext();
}
package com.pattern.Iterator;
import java.util.ArrayList;
/** * @author wlj * @Classname ClassroomIterator * @Description Specific iterators * @Date 7/25/2022 11:04 AM */
public class ConcreteIterator implements Iterator{
private ArrayList<Object> list = null;
private int index = -1;
public ConcreteIterator(ArrayList<Object> list) {
this.list = list;
}
@Override
public Object first() {
index = 0;
Object object = list.get(index);
return object;
}
@Override
public Object next() {
Object object = null;
if(this.hasNext()){
object = list.get(++index);
}
return object;
}
@Override
public boolean hasNext() {
if (index < list.size() - 1) {
return true;
} else {
return false;
}
}
}
package com.pattern.Iterator;
/** * @author wlj * @Classname Student * @Description Aggregate target students * @Date 7/25/2022 10:58 AM */
public class Student {
// student name
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
package com.pattern.Iterator;
import java.util.ArrayList;
/** * @author wlj * @Classname Client * @Description test * @Date 7/25/2022 11:20 AM */
public class Client {
public static void main(String[] args) {
Aggregate classroom = new ConcreteAggregate();
classroom.addAggregate(new Student(" Xiao Ming "));
classroom.addAggregate(new Student(" Xiaohong "));
classroom.addAggregate(new Student(" floret "));
Iterator it = classroom.getIterator();
while (it.hasNext()) {
// index The default is -1, The first element is index=0
Object obj = it.next();
System.out.println(obj.toString());
}
Student first = (Student) it.first();
System.out.println(first.toString());
}
}
// Output
Student{
name=' Xiao Ming '}
Student{
name=' Xiaohong '}
Student{
name=' floret '}
Student{
name=' Xiao Ming '}
application
- Java Medium Collection、List、Set、Map And so on all contain iterators .jdk Iterators have been provided , We generally don't need to realize .
边栏推荐
- Taobao flexible.js file realizes flexible layout
- After entering www.baidu.com in the address bar
- Read the field status of account in ABAP code (hidden, optional, required)
- firewall 命令简单操作
- Scroll series
- 赋值时'1和'b1有什么区别
- Matchmaker's words
- Leetcode 0135. distribute candy
- [learning notes] unreal 4 engine introduction (III)
- S4/hana mm & SD EDI Nast based integrated configuration (orders, ordrsp, desadv, invoice)
猜你喜欢

SIGIR '22 recommendation system paper graph network

LeetCode 0135. 分发糖果

S4/hana mm & SD EDI Nast based integrated configuration (orders, ordrsp, desadv, invoice)
![[learning notes] unreal 4 engine introduction (III)](/img/c2/2e6023c72652c77577f8f21684d07e.png)
[learning notes] unreal 4 engine introduction (III)

ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve

Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms

The GUI interface of yolov3 (simple, image detection)

SQLZOO——Nobel Quiz

二叉树——257. 二叉树的所有路径

SIGIR‘22 推荐系统论文之图网络篇
随机推荐
R language installation tutorial | graphic introduction is super detailed
[learning notes] solid works operation record
二叉树——654. 最大二叉树
你还在用浏览器自带书签?这款书签插件超赞
Demo of pointer function
Part 74: overview of machine learning optimization methods and superparameter settings
firewall 命令简单操作
【英雄哥七月集训】第 24天: 线性树
二叉树——226. 翻转二叉树
@The underlying principle of Autowired annotation
The late Apple co-founder Steve Jobs was posthumously awarded the U.S. presidential medal of freedom
arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置
2022-07-18 study notes of group 5 self-cultivation class (every day)
[Muduo] package EventLoop and thread
Good news under the epidemic
二叉树——112. 路径总和
How does JS judge whether the current date is within a certain range
程序员面试金典 4.12 求和路径
开放API生态系统面临的十个威胁
Optimize the browsing experience of yandere/konachan site with user scripts