迭代器模式

【迭代器模式】 迭代器可以顺序访问一个聚集中的元素而不必显露聚集的内部对象。多个对象聚在一起形成的总体称为聚集,聚集对象是能够包容一组对象的容器对象。迭代器模式将迭代逻辑封装到一个独立的对象中,从而与聚集本身隔开。迭代算法独立于聚集对象,修改迭代算法不会对聚集对象产生任何影响,实现程序的松耦合。


1.Aggregate接口所声明的方法只有iterator方法一个,这是为了建立一个对对应聚合的
iterator
Java代码
1. package com.pattern.iterator;
2.
3. public interface Aggregate {
4. public abstract Iterator iterator();
5. }


2.iterator接口,执行元素递增,具有类似循环变量的功能。
Java代码
1. package com.pattern.iterator;
2. public interface Iterator {
3. public abstract boolean hasNext();
4. public abstract Object next();
5. }


3. 书籍类
Java代码
1. package com.pattern.iterator;
2. public class Book {
3. private String name="";
4.
5. public Book(String name) {
6. this.name = name;
7. }
8.
9. /**
10. * 获得书籍名称
11. * @return String
12. */
13. public String getName() {
14. return name;
15. }
16. }


4.书架类
Java代码
1. package com.pattern.iterator;
2. /**
3. * 书架类
4. * @author administrator
5. */
6. public class BookShelf implements Aggregate{
7. private Book[] books;
8. private int last = 0;
9.
10. public BookShelf(int maxSize) {
11. this.books = new Book[maxSize];
12. }
13.
14. public Book getBookAt(int index) {
15. return books[index];
16. }
17.
18. //添加书籍
19. public void appendBook(Book book) {
20. this.books[last] = book;
21. last++;
22. }
23. //获得书架存书的数量
24. public int getLength() {
25. return books.length;
26. }
27. //获得书架迭代器对象
28. public Iterator iterator() {
29. return new BookShelfIterator(this);
30. }
31.
32. }

5.书架迭代器类
Java代码
1. package com.pattern.iterator;
2. public class BookShelfIterator implements Iterator{
3. private BookShelf bookShelf;
4. private int index;
5.
6. public BookShelfIterator(BookShelf bookShelf) {
7. this.bookShelf = bookShelf;
8. this.index = 0;
9. }
10.
11. //检查是否还有下一本书
12. public boolean hasNext() {
13. if(index < bookShelf.getLength()) {
14. return true;
15. }
16. else {
17. return false;
18. }
19. }
20. //返回指定位置的书籍
21. public Object next() {
22. Book book = bookShelf.getBookAt(index);
23. index ++;
24. return book;
25. }
26. }


6.测试类
Java代码
1. package com.pattern.iterator;
2.
3. public class Main {
4. public static void main(String[] args) {
5. //生成一个书架
6. BookShelf bookShelf = new BookShelf(4);
7. //向书架添加书籍
8. bookShelf.appendBook(new Book("Effective Java"));
9. bookShelf.appendBook(new Book("J2EE"));
10. bookShelf.appendBook(new Book("Head First Design Pattern"));
11. bookShelf.appendBook(new Book("Thinking in Java"));
12.
13. //获得书架迭代器
14. Iterator it = bookShelf.iterator();
15. while(it.hasNext()) {
16. Book book = (Book)it.next();
17. System.out.println(book.getName());
18. }
19. }
20. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值