设计模式之迭代器模式(行为型)
【摘要】
文章目录
一、模式定义二、模式角色三、模式分析四、典型例子五、适用场景
一、模式定义
迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor),所以迭代器模式是一种对象行为型。
二、模式角色
Iterator:抽象迭代器ConcreteIterator:具体迭代器...
一、模式定义
迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor),所以迭代器模式是一种对象行为型。
二、模式角色
- Iterator:抽象迭代器
- ConcreteIterator:具体迭代器
- Aggregate:抽象聚合类
- ConcreteAggregate:具体聚合类
三、模式分析
对于迭代器模式来说,一个聚合可以有多个遍历。在迭代器模式中,提供了一个外部的迭代器对聚合对象进行访问和遍历,迭代器定义了一个访问聚合对象的接口,可以跟踪遍历元素,了解哪些元素已经遍历过而哪些没有。
迭代器模式中应用了工厂方法模式,聚合类充当工厂类,而迭代器充当产品类
迭代器模式本质
迭代器模式本质:将聚合对象存储的内部数据提取出来,封装到一个迭代器中,通过专门的迭代器来遍历聚合对象的内部数据,这就是迭代器模式的本质
聚合对象主要职责
聚合对象主要有两个职责:一是存储内部数据;二是遍历内部数据;最基本的职责还是存储内部数据
四、典型例子
例子来自:《设计模式》一书
自定义迭代器
自定义迭代器
Client:客户端调用
MyIterator:抽象迭代器
MyCollection:抽象聚合类
NewCollection:具体聚合类
NewIterator:具体迭代器
interface MyCollection
{
MyIterator createIterator();
}
interface MyIterator
{
void first();
void next();
boolean isLast();
Object currentItem();
}
class NewCollection implements MyCollection
{ private Object[] obj={"dog","pig","cat","monkey","pig"}; public MyIterator createIterator() { return new NewIterator(); } private class NewIterator implements MyIterator { private int currentIndex=0; public void first() { currentIndex=0; } public void next()
{
if(currentIndex<obj.length)
{ currentIndex++;
}
} public void previous()
{
if(currentIndex>0)
{ currentIndex--;
}
} public boolean isLast()
{
return currentIndex==obj.length;
} public boolean isFirst()
{
return currentIndex==0;
} public Object currentItem()
{
return obj[currentIndex];
} }
}
class Client
{
public static void process(MyCollection collection)
{
MyIterator i=collection.createIterator(); while(!i.isLast())
{ System.out.println(i.currentItem().toString()); i.next();
}
} public static void main(String a[])
{
MyCollection collection=new NewCollection();
process(collection);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
五、适用场景
在以下的情况可以使用迭代器模式:
- 访问一个聚合对象的内容而无须暴露它的内部表示。
- 需要为聚合对象提供多种遍历方式。
- 为遍历不同的聚合结构提供一个统一的接口。
文章来源: smilenicky.blog.csdn.net,作者:smileNicky,版权归原作者所有,如需转载,请联系作者。
原文链接:smilenicky.blog.csdn.net/article/details/89289395
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)