作甚迭代器形式?
迭代器供給了一種次序拜訪聚集對象中元素的辦法,而無需暴漏構造的底層表現和細節。遍歷聚集中元素的本能機能從聚集自己轉移到迭代器對象。迭代器界說了一個用於拜訪聚集元素並記載以後元素的接口。分歧的迭代器可以履行分歧的戰略。
例子
說了這麼多,上面給年夜家展現一下類關系圖。
上圖中Client的左邊是迭代器,右邊是詳細迭代的類型,在迭代器外部對詳細須要迭代的類型停止了援用,還算不難懂得吧,呵呵。其實,看起來是為了對詳細類型停止解耦。好啦,上面給出詳細的代碼完成,簡略的模仿了迭代器形式。
留意:本文一切代碼均在ARC情況下編譯經由過程。
Iterator類接口
#import <Foundation/Foundation.h>
@interface Iterator:NSObject
-(id)First;
-(id)Next;
-(BOOL)IsDone;
-(id)CurrentItem;
@end
Iterator類完成
#import "Iterator.h"
@implementation Iterator
-(id)First{
return nil;
}
-(id)Next{
return nil;
}
-(BOOL)IsDone{
return NO;
}
-(id)CurrentItem{
return nil;
}
@end
ConcreteIterator類接口
#import "Iterator.h"
@class ConcreteAggregate;
@interface ConcreteIterator :Iterator{
ConcreteAggregate *myAggregate;
int current;
}
-(ConcreteIterator*)MyInit:(ConcreteAggregate*)aggregate;
@end
ConcreteIterator類完成
#import "ConcreteIterator.h"
#import "ConcreteAggregate.h"
@implementation ConcreteIterator
-(ConcreteIterator*)MyInit:(ConcreteAggregate*)aggregate{
myAggregate = aggregate;
return self;
}
-(id)First{
return [myAggregate GetObject:0];
}
-(id)Next{
current++;
if(current< [myAggregate GetCount])
return [myAggregate GetObject:current];
else {
return nil;
}
}
-(BOOL)IsDone{
return current>= [myAggregate GetCount] ?YES:NO;
}
-(id)CurrentItem{
return [myAggregate GetObject:current];
}
@end
Aggregate類接口
#import <Foundation/Foundation.h>
@class Iterator;
@interface Aggregate:NSObject
-(Iterator*)CreateIterator;
@end
Aggregate類完成
#import "Aggregate.h"
#import "Iterator.h"
@implementation Aggregate
-(Iterator*)CreateIterator{
return [[Iterator alloc]init];
}
@end
ConcreteAggregate類接口
#import "Aggregate.h"
@interface ConcreteAggregate:Aggregate{
NSMutableArray *items;
}
-(int)GetCount;
-(id)GetObject:(int)index;
-(void)InsertObject:(id)Obj;
@end
ConcreteAggregate類完成
#import "ConcreteAggregate.h"
#import "Iterator.h"
@implementation ConcreteAggregate
-(id)init{
if(self == [super init]){
items = [NSMutableArray new];
}
return self;
}
-(Iterator*)CreateIterator{
return [[Iterator alloc]init];
}
-(id)GetObject:(int)index{
return [items objectAtIndex:index];
}
-(void)InsertObject:(id)Obj{
[items addObject:Obj];
}
-(int)GetCount{
return [items count];
}
@end
Main辦法挪用
import <Foundation/Foundation.h>
#import "ConcreteAggregate.h"
#import "Iterator.h"
#import "ConcreteIterator.h"
int main (int argc, const char *argv[])
{
@autoreleasepool {
ConcreteAggregate *a = [[ConcreteAggregate alloc]init];
[a InsertObject:@"張三"];
[a InsertObject:@"李四"];
[a InsertObject:@"王二"];
[a InsertObject:@"麻子"];
NSLog(@"Count:%d", [a GetCount]);
Iterator *i = [[ConcreteIterator alloc]MyInit:a];
while (![i IsDone]) {
NSLog(@"%@,請買票",[i CurrentItem]);
[i Next];
}
}
return 0;
}
好啦,下面的四個類型簡略完成了迭代器形式,其實迭代器形式就是分別了聚集對象的遍歷行動,籠統出一個迭代器類來擔任,如許既可以做到不裸露聚集的外部構造,又可讓內部代碼通明地拜訪聚集外部地數據。
什麼時候應用迭代器形式?
1.須要拜訪組合對象的內容,而又不暴漏其外部表現。
2.須要經由過程多種方法遍歷組合對象。
3.須要供給一個同一的接口,用來遍歷各類類型的組合對象。
【iOS App設計形式開辟中對迭代器形式的應用示例】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!