Iterator - one by one

概述:

一个一个遍历

iterator_sample


说明:

1.本文仅仅是对 图解设计模式 的简单总结(个人笔记).
2.文章中的图片均来自本书,添加水印只是为了防止盗链行为,并无侵权的想法.
综上,若侵权, 请联系删除!
转载请标注出处!


案例:

  • 说明:模拟将书放回书架
  • iterator_uml
  • 主要代码如下:
    • BookShelfIterator.java
      package Gof.iterator;
      
      public class BookShelfIterator implements Iterator {
          private BookShelf bookShelf;
          private int index;
          public BookShelfIterator(BookShelf bookShelf) {
              this.bookShelf = bookShelf;
              this.index = 0;
          }
          public boolean hasNext() {
              if (index < bookShelf.getLength()) {
                  return true;
              } else {
                  return false;
              }
          }
          public Object next() {
              Book book = bookShelf.getBookAt(index);
              index++;
              return book;
          }
      }
      
      代码链接:传送门

  • uml综述

     ![iterator_uml](/resource/iterator_uml.png)
  • 说明:

    1.Iterator(迭代器) 按照顺序逐个遍历元素的api

    2.ConcreteIterator(具体的迭代器) 实现Iterator 定义的api

    3.Aggregate(集合):定义创建Iterator 角色的api

    4.ConcreteAggregate(具体的集合):实现Aggregate角色所定义的的API

收获:

  1. 不要只使用具体类来编程,要优先使用抽象类和接口
  2. next 方法: 返回当前元素,并指向下一个
  3. hasNext 方法: 确认接下来是否可以调用next方法
  4. 不需要deleteIterator (reason : java gc )

相关设计模式:

  • Visit :
  • Composite:
  • Factory Method :

注意:

此部分内容属于对GOF Design Pattern知识的初步认知阶段,参考书籍是结城浩的《图解设计模式》,简单易懂,十分推荐!
以上内容,作者一字一句码出来的,纯属不易,欢迎大家转载,转载是还请您表明出处。另外如果我有侵权行为,请在下方留言,确认后我会及时撤销相应内容,谢谢大家!

PS:欢迎大家来到我的小站,鸣谢!