Java 之 23 种设计模式解析——16、迭代子模式(Iterator)

16、迭代子模式(Iterator)

顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。这句话包含两层意思:一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。我们看下关系图:

 

这个思路和我们常用的一模一样,MyCollection中定义了集合的一些操作,MyIterator中定义了一系列迭代操作,且持有Collection实例,我们来看看实现代码:

两个接口:

1. public interface Collection {
2.
3.	public Iterator iterator();
4.
5.	/*取得集合元素*/
6.	public Object get(int i);
7.
8.	/*取得集合大小*/
9.	public int size();
10. }
1. public interface Iterator {
2.	//前移
3.	public Object previous();
4.
5.	//后移
6.	public Object next();
7.	public boolean hasNext();
8.
9.	//取得第一个元素
10.	public Object first();

两个实现:

1. public class MyCollection implements Collection {
2.
3.	public String string[] = {"A","B","C","D","E"};
4.	@Override
5.	public Iterator iterator() {
6.	return new MyIterator(this);
7.	}
8.
9.	@Override
10.	public Object get(int i) {
11.	return string[i];
12.	}
13.
14.	@Override
15.	public int size() {
16.	return string.length;
17.	}
18. }
1. public class MyIterator implements Iterator {
2.
3.	private	Collection	collection;
4.	private	int	pos	=	-1;
5.
6.	public MyIterator(Collection collection){
7.	this.collection = collection;
8.	}
9.
10.	@Override
11.	public Object previous() {
12.	if(pos > 0){
13.	pos--;
14.	}
15.	return collection.get(pos);
16.	}
17.
18.	@Override
19.	public Object next() {
20.	if(pos<collection.size()-1){
21.	pos++;
22.	}
23.	return collection.get(pos);
24.	}
25.
26.	@Override
27.	public boolean hasNext() {
28.	if(pos<collection.size()-1){
29.	return true;
30.	}else{
31.	return false;
32.	}
33.	}
34.
35.	@Override
36.	public Object first() {
37.	pos = 0;
38.	return collection.get(pos);
39.	}
40.
41. }

测试类:

1. public	class	Test	{
2.
3.	public	static	void	main(String[]	args)	{
4.	Collection	collection	=	new	MyCollection();
5.	Iterator	it	=	collection.iterator();
6.
7.	while(it.hasNext()){
8.	System.out.println(it.next());
9.	}
10.	}
11. }

输出:A B C D E

此处我们貌似模拟了一个集合类的过程,感觉是不是很爽?其实JDK中各个类也都是这些基本的东西,加一些设计模式,再加一些优化放到一起的,只要我们把这些东西学会了,掌握好了,我们也可以写出自己的集合类,甚至框架!

目录:(点击进入相应页面)

概述、六大原则

一、创建模式

0、简单工厂模式

1.工厂方法模式(Factory Method)

2、抽象工厂模式

3、单例模式(Singleton)

4、建造者模式(Builder)

5、原型模式(Prototype)

二、结构模式(7种)

6、适配器模式

7、装饰模式(Decorator)

8、代理模式(Proxy)

9、外观模式(Facade)

10、桥接模式(Bridge)

11、组合模式(Composite

12、享元模式(Flyweight)

三、关系模式(11种)

13、策略模式(strategy)

14、模板方法模式(Template Method)

15、观察者模式(Observer)

16、迭代子模式(Iterator)

17、责任链模式(Chain of Responsibility)

18、命令模式(Command)

19、备忘录模式(Memento

20、状态模式(State)

21、访问者模式(Visitor)

22、中介者模式(Mediator)

23、解释器模式(Interpreter)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值