Iterator(迭代器模式)
提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
iOS的Block迭代、数组迭代都是迭代器模式的典型实现。
设计迭代器之前需要搞清楚线性表中的顺序表与链表的相关内容,参考:顺序表与链表的区别
系统的迭代器
//创建集合对象
NSArray *datas = @[@"A", @"B", @"C", @"D"];
//从集合对象创建迭代器
NSEnumerator *iterator = [datas objectEnumerator];
//从集合对象中访问元素
id arrayObj = nil;
while (arrayObj = [iterator nextObject]) {
NSLog(@"arrayObj:%@", arrayObj);
}
打印结果:A,B,C,D
自定义迭代器
- 创建节点类和链表类
Node.h
@interface Node : NSObject
// 指向下一个节点
@property (strong, nonatomic) Node *nextNode;
// 节点的对象
@property (strong, nonatomic) id item;
// 类构造方法
+ (instancetype)nodeWithItem:(id)item;
@end
Node.m
@implementation Node
+ (instancetype)nodeWithItem:(id)item {
// 这里之所以用self关键字来开辟对象,是考虑到有继承问题
Node *node = [[[self class] alloc] init];
node.item = item;
return node;
}
@end
LinkedList.h
@interface LinkedList : NSObject
// 头节点
@property (strong, nonatomic, readonly) Node *headNode;
// 有几个节点
@property (readonly, nonatomic) NSInteger numberOfNodes;
// 节点挂载的对象
- (void)addItem:(id)item;
@end
LinkedList.m
@interface LinkedList()
@property (strong, nonatomic) Node *headNode;
@property (assign, nonatomic) NSInteger numberOfNodes;
@end
@implementation LinkedList
- (instancetype)init {
self = [super init];
if (self) {
self.headNode = [Node new];
}
return self;
}
- (void)addItem:(id)item {
if (self.headNode == nil) {
self.headNode = [Node nodeWithItem:item];
} else {
[self addItem:item node:self.headNode];
}
}
- (void)addItem:(id)item node:(Node *)node {
if (node.nextNode == nil) {
node.nextNode = [Node nodeWithItem:item];
} else {
[self addItem:item node:node.nextNode];
}
}
@end
- 创建一个迭代器协议类
IteratorProtocol.h
@protocol IteratorProtocol <NSObject>
@required
//下一个对象
- (id)nextObject;
@end
- 创建迭代器
LinkedListIterator.h
@interface LinkedListIterator : NSObject <IteratorProtocol>
// 返回一个链表迭代器的构造器
+ (instancetype)linkedListIteratorWithLinkedList:(LinkedList *)linkedList;
@end
LinkedListIterator.m
@interface LinkedListIterator()
@property (strong, nonatomic) LinkedList *linkedList;
@property (strong, nonatomic) Node *currentNode;
@end
@implementation LinkedListIterator
+ (instancetype)linkedListIteratorWithLinkedList:(LinkedList *)linkedList {
LinkedListIterator *linkedListIterator = [LinkedListIterator new];
linkedListIterator.linkedList = linkedList;
linkedListIterator.currentNode = linkedList.headNode;
return linkedListIterator;
}
- (id)nextObject {
self.currentNode = self.currentNode.nextNode;
return self.currentNode;
}
@end
- 实现
VC.m
LinkedList *linkList = [[LinkedList alloc] init];
[linkList addItem:@"A"];
[linkList addItem:@"B"];
[linkList addItem:@"C"];
[linkList addItem:@"D"];
// 从集合对象创建迭代器
LinkedListIterator *iterator = [LinkedListIterator linkedListIteratorWithLinkedList:linkList];
// 从集合对象中访问元素
Node *node = nil;
while (node = [iterator nextObject]) {
NSLog(@"---- %@", node.item);
}