Iterator(迭代器模式)
提供一種方法順序訪問一個聚合對象中各個元素剂癌,而又不暴露該對象的內(nèi)部表示哪自。
iOS的Block迭代线得、數(shù)組迭代都是迭代器模式的典型實現(xiàn)顶霞。
設(shè)計迭代器之前需要搞清楚線性表中的順序表與鏈表的相關(guān)內(nèi)容尿褪,參考:順序表與鏈表的區(qū)別
系統(tǒng)的迭代器
//創(chuàng)建集合對象
NSArray *datas = @[@"A", @"B", @"C", @"D"];
//從集合對象創(chuàng)建迭代器
NSEnumerator *iterator = [datas objectEnumerator];
//從集合對象中訪問元素
id arrayObj = nil;
while (arrayObj = [iterator nextObject]) {
NSLog(@"arrayObj:%@", arrayObj);
}
打印結(jié)果:A,B,C,D
自定義迭代器
- 創(chuàng)建節(jié)點類和鏈表類
Node.h
@interface Node : NSObject
// 指向下一個節(jié)點
@property (strong, nonatomic) Node *nextNode;
// 節(jié)點的對象
@property (strong, nonatomic) id item;
// 類構(gòu)造方法
+ (instancetype)nodeWithItem:(id)item;
@end
Node.m
@implementation Node
+ (instancetype)nodeWithItem:(id)item {
// 這里之所以用self關(guān)鍵字來開辟對象睦擂,是考慮到有繼承問題
Node *node = [[[self class] alloc] init];
node.item = item;
return node;
}
@end
LinkedList.h
@interface LinkedList : NSObject
// 頭節(jié)點
@property (strong, nonatomic, readonly) Node *headNode;
// 有幾個節(jié)點
@property (readonly, nonatomic) NSInteger numberOfNodes;
// 節(jié)點掛載的對象
- (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
- 創(chuàng)建一個迭代器協(xié)議類
IteratorProtocol.h
@protocol IteratorProtocol <NSObject>
@required
//下一個對象
- (id)nextObject;
@end
- 創(chuàng)建迭代器
LinkedListIterator.h
@interface LinkedListIterator : NSObject <IteratorProtocol>
// 返回一個鏈表迭代器的構(gòu)造器
+ (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
- 實現(xiàn)
VC.m
LinkedList *linkList = [[LinkedList alloc] init];
[linkList addItem:@"A"];
[linkList addItem:@"B"];
[linkList addItem:@"C"];
[linkList addItem:@"D"];
// 從集合對象創(chuàng)建迭代器
LinkedListIterator *iterator = [LinkedListIterator linkedListIteratorWithLinkedList:linkList];
// 從集合對象中訪問元素
Node *node = nil;
while (node = [iterator nextObject]) {
NSLog(@"---- %@", node.item);
}