• 【图解设计模式】迭代器模式


    Iterator模式用于在数据集合中按照顺序遍历集合

    实例程序:将book放置到书架上,并按顺序显示

     

    1. public interface Aggregate {
    2. public abstract Iterator iterator();
    3. }
    1. public class Book {
    2. private String name;
    3. public Book(String name){
    4. this.name=name;
    5. }
    6. public String getName(){
    7. return name;
    8. }
    9. }
    1. public class BookShelf implements Aggregate {
    2. private Book[]books;
    3. private int last=0;
    4. public BookShelf(int maxSize){
    5. this.books=new Book[maxSize];
    6. }
    7. public Book getBookAt(int index){
    8. return books[index];
    9. }
    10. public void appendBook(Book book){
    11. this.books[last]=book;
    12. last++;
    13. }
    14. public int getLength(){
    15. return last;
    16. }
    17. @Override
    18. public Iterator iterator(){
    19. return new BookShelfIterator(this);
    20. }
    21. }
    1. public class BookShelfIterator implements Iterator {
    2. private BookShelf bookShelf;
    3. private int index;
    4. public BookShelfIterator(BookShelf bookShelf){
    5. this.bookShelf=bookShelf;
    6. this.index=0;
    7. }
    8. @Override
    9. public boolean hasNext(){
    10. if(indexreturn true;
    11. else return false;}
    12. @Override
    13. public Object next(){
    14. Book book = bookShelf.getBookAt(index);
    15. index++;
    16. return book;
    17. }
    18. }
    1. public interface Iterator {
    2. public abstract boolean hasNext();
    3. public abstract Object next();
    4. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. BookShelf bookShelf=new BookShelf(4);
    4. bookShelf.appendBook(new Book("a"));
    5. bookShelf.appendBook(new Book("b"));
    6. bookShelf.appendBook(new Book("c"));
    7. Iterator it=bookShelf.iterator();
    8. while(it.hasNext()){
    9. Book book =(Book)it.next();
    10. System.out.println(book.getName());
    11. }
    12. }

    【角色说明】

    【Iterator】定义按顺序逐个遍历元素的接口(API)

    【ConcreteIterator】负责实现Iterator角色所定义的接口。该角色中包含了遍历集合所必需的信息

    Aggregate】负责定义创建Iterator角色的接口。里面定义了iterator方法

    【ConcreteAggregate】集合

     引入Iterator后可以将遍历和实现分离开

     这里只使用了Iterator的hasNext方法和next方法,并没有调用BookShelf的方法,就是说不依赖集合的实现。只要具体的集合的iterator方法能正确的返回Iterator实例,不对while做修改也可以。

    “可复用”。

    “面对接口编程”

    【next方法】返回当前元素,并指向下一个元素

    【hasNext方法】确认接下来是否可以调用next方法。

    【迭代器的种类多种多样】遍历方法可以从前向后,从后向前或者跳跃式遍历

    【不需要deleteIterator】java中,没有被使用的对象实例会被自动删除。

    手写迭代器模式的注意点 

  • 相关阅读:
    MyBatis-Plus删除操作知识点总结
    基于STM32设计的小龙虾养殖系统(带手机APP)
    使用不同尺寸的传感器拍照时,怎么保证拍出同样视场范围的照片?
    sqlsession对象为什么不能被共享?
    DVWA-JavaScript Attacks
    Spring Boot项目开发实战:Spring Boot中的MVC支持
    世界上最便宜好用的服务器低至 $9.99 / 年
    计算机遇到MSVCP140.dll丢失问题?全面分析解决方案
    经典算法之冒泡排序法与直接选择排序法
    【问题解决】容器部署MySQL的数据在docker commit导出的镜像中丢失
  • 原文地址:https://blog.csdn.net/m0_52043808/article/details/126721471