设计模式-迭代器模式

定义

提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。

迭代器模式通用类图

Iterator通用类图

角色

Iterator(迭代器)

该角色负责定义按顺序逐个遍历元素的接口。

ConcreteIterator(具体的迭代器)

该角色负责实现 Iterator 角色所定义的接口。

Aggregate(集合)

该角色负责定义创建 Iterator 角色的接口。

ConcreteAggregate(具体的集合)

该角色负责实现 Aggregate 角色所定义的接口。

迭代器模式,将遍历与实现分离开来。

实现

Iterator实现

/**
*定义 迭代器 接口
*/
public interface Iterator<T> {
	boolean hasNext();
	T next();
}

/**
*定义 聚合 接口
*/
public interface Aggregate<T> {
	Iterator<T> iterator();
}

/**
* 具体的集合
*/
public class BookShel<T> implements Aggregate<T> {
	private Object[] objects;
	private int last = 0;
	public BookShelf(int maxsize) {
		this.objects = new Object[maxsize];
	}
	
	@SuppressWarnings("unchecked")
	public T getAt(int index) {
		return (T)objects[index];
	}
	
	public void append(T t) {
		this.objects[last] = t;
		last++;
	}
	
	public int getLength() {
		return last;
	}
	
	@Override
	public Iterator<T> iterator() {
		return new BookShelfIterator<T>(this);
	}
}

/**
* 具体的迭代器
*/
public class BookShelfIterator<T> implements Iterator<T>{
	
	private BookShelf<T> bookShelf;

	private int index;
	
	public BookShelfIterator(BookShelf<T> bookShelf) {
		this.bookShelf = bookShelf;
		this.index = 0;
	}

	@Override
	public boolean hasNext() {
		if (index < bookShelf.getLength()) {
			return true;
		}
		return false;
	}

	@Override
	public T next() {
		T obj = bookShelf.getAt(index);
		index++;
		return obj ;
	}

}

/**
* 实体类
*/
public class Book {
	private String name;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public Book(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "Book [name=" + name + "]";
	}
}

/**
* main方法
*/
public class IteratorMain {
	
	public static void main(String[] args) {
		BookShelf<Book> bookShelf = new BookShelf<Book>(10);
		Book book = new Book("九阴真经");
		bookShelf.append(book);
		Book book1 = new Book("天龙八部");
		bookShelf.append(book1);
		Iterator<Book> iterators = bookShelf.iterator();
		while (iterators.hasNext()) {
			Book nextBook = iterators.next();
			System.out.println(nextBook);		
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值