美文网首页
Iterator模式

Iterator模式

作者: 492284513d5a | 来源:发表于2019-01-14 20:37 被阅读0次

Iterator模式用于在数据集合中按照顺序遍历集合。英语单词Iterate有重复做某件事情的意思。也叫做“迭代器”。

登场角色

  • Iterator(迭代器)

该角色负责定义按顺序逐个遍历元素的接口(API)。在下图中由Iterator接口扮演这个角色,它定义了hasNext和next两个方法。

  • Iterator接口

public interface Iterator{
   public abstract boolean hasNext();
   public abstract Object next();
}
  • ConcreteIterator(具体的迭代器)

该角色负责实现Iterator角色所定义的接口(API)。在示例中,由BookShelfIterator类扮演这个角色。该角色包含了遍历集合所必需的信息。

  • BookShelfIterator类

public class BookShelfIterator implments 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;
   } 
}
  • Aggregate(集合)

该角色负责定义创建Iterator角色的接口(API)。这个接口是一个方法,会创建出“按顺序访问保存在我内部元素的人”。在示例程序中由Aggregate接口扮演这个角色,它里面定义了iterator方法。

  • Aggregate接口

public interface Aggregate{
    public abstract Iterator iterator();
}
  • ConcreteAggregate(具体的集合)

该角色负责实现Aggregate角色所定义的接口(API)。它会创建具体的Iterator角色,在示例的程序中,由BookShelf类 扮演这个角色。

  • BookShelf类

public class BookShelf implements Aggregate{
    private Book[] books;
    private int last = 0;
    public BookShelf(int maxsize){
        this.books = new Book[maxsize];
    }
    public Book getBookAt(int index){
        return books[index]      
      }
    public void appendBook(Book book){
        this.books[last] = book;
        last++
  }
   public int getLength(){
        return last;
   }
   public Iterator iterator(){
        return new BookShelfIterator(this);
   }
}
Iterator.png

相关文章

  • Iterator模式

    迭代器模式(Iterator模式) 定义: 迭代器(Iterator)模式,又叫做游标(Cursor)模式。 ...

  • 设计模式用例(三)

    Strategy 模式 Bridge 模式 Iterator 模式

  • 编程思想

    图解设计模式 Iterator 模式 设计模式 Iterator 模式如何提升你的阅读能力? 导读:今天这篇文章是...

  • 函数式编程下的Iterator模式

    在模式下,Iterator模式是一个思路相对简单的模式。迭代器(Iterator)模式,又叫做游标(Cursor)...

  • 迭代器模式 Iterator Pattern

    迭代器模式(Iterator Pattern)属于行为型模式。Iterator pattern 提供了循环集合的标...

  • 1. Iterator模式-一个一个遍历

    时间: 2019-04-29 1.1 Iterator模式概念 Iterator模式: 用于在数据集合中按照顺序遍...

  • Design(一)-Iterator设计模式

    Iterator设计模式 简介: Iterator设计模式在数据集合中按照顺序遍历集合. 英语单词Iterate有...

  • 图解设计模式Iterator模式

    Iterator设计模式UML图 Iterator(迭代器) ConcreteIterator(具体的迭代器) A...

  • iterator模式

    类似于stl里面的迭代器 iterator.h #ifndef _ITERATOR_H#define _ITERA...

  • Iterator模式

    Iterator模式用于在数据集合中按照顺序遍历集合。英语单词Iterate有重复做某件事情的意思。也叫做“迭代器...

网友评论

      本文标题:Iterator模式

      本文链接:https://www.haomeiwen.com/subject/tagjdqtx.html