概念
迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
迭代器模式属于行为型模式。
参考链接: 迭代器模式 | 菜鸟教程
代码案例
设计迭代器接口,有两个方法hasNext,next
/**
* 迭代器类
*/
public interface Iterator {
boolean hasNext();
Object next();
}
容器接口,获取迭代器
/**
* 容器类
*/
public interface Container {
Iterator getIterator();
}
集合容器,内部类实现迭代器功能
/**
* 车子集合,提供迭代器功能
*/
@Slf4j
public class CarsList implements Container {
private String[] carsArr;
public CarsList(String[] carsArr) {
this.carsArr = carsArr;
}
@Override
public Iterator getIterator() {
return new CarsIterator();
}
private class CarsIterator implements Iterator{
int index;
@Override
public boolean hasNext() {
if (index<carsArr.length){
log.info("carsArr has next ");
return true;
}
return false;
}
@Override
public Object next() {
if (this.hasNext()){
String perCars = carsArr[index++];
log.info("current cars is : {}",perCars);
return perCars;
}
return null;
}
}
}
测试主类
/**
* 设计模式控制器
*/
@RestController
@RequestMapping("/designPattern")
@Slf4j
public class DesignController {
@PostMapping("/iterator")
public ResponseModel iterator(@RequestBody String[] carsArr) {
log.info("iterator ---- start ");
List list= new ArrayList();
CarsList carsList = new CarsList(carsArr);
Iterator iterator = carsList.getIterator();
while (iterator.hasNext()){
String perCars = (String) iterator.next();
list.add(perCars);
}
log.info("iterator ---- end ");
return new ResponseModel("迭代器模式完成", 200, list);
}
}
测试案例
2022-06-30 00:49:12.128 INFO iterator ---- start 【http-nio-8081-exec-1】【DesignController:75】
2022-06-30 00:49:12.133 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.133 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.134 INFO current cars is : BMW 【http-nio-8081-exec-1】【CarsList:39】
2022-06-30 00:49:12.134 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.134 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.134 INFO current cars is : Giant 【http-nio-8081-exec-1】【CarsList:39】
2022-06-30 00:49:12.134 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.135 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.138 INFO current cars is : Benz 【http-nio-8081-exec-1】【CarsList:39】
2022-06-30 00:49:12.138 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.138 INFO carsArr has next 【http-nio-8081-exec-1】【CarsList:29】
2022-06-30 00:49:12.139 INFO current cars is : Merida 【http-nio-8081-exec-1】【CarsList:39】
2022-06-30 00:49:12.139 INFO iterator ---- end 【http-nio-8081-exec-1】【DesignController:83】