iOS設計模式之—適配器模式
一、何為適配器模式
在我們做項目的時候,會遇到一些相同的cell視圖,但是數據源不同。比較傳統的寫法就是在cell中寫兩個Model的方法用于給視圖傳遞值,這種方法可行,但不是最佳,如果后期其他的頁面也需要用到這個cell,我們又要在cell中再寫一個Model方法,不利于后期的迭代,而且代碼的耦合度太高。這個時候就要用到我們的適配器了。
適配器,用于連接兩種不同類的對象,使其能夠協同工作。
類適配器OMT圖示法(請忽略我的文字,丑的我都不想看)
二、何時使用適配器
- 已有的接口與需求不匹配
- 想要一個可復用的類,該類能夠和其他不謙容的類協作
- 需要適配一個類的幾個不同的子類,可以使用對象適配器適配父類的接口
三、實現
1.協議方法
定義要適配的接口
@protocol AdapterProtocol <NSObject>
- (NSString *)title;
- (UIImage *)headImage;
@end</code></pre>
2.根適配器
定義被適配的數據源類,遵守AdapterProtocol協議,并重載協議方法
#import"AdapterProtocol.h"
@interfaceRootAdapter :NSObject<AdapterProtocol>
@property(weak,nonatomic)id data;
- (instancetype)initWithData:(id)data;
@end
@implementationRootAdapter
- (instancetype)initWithData:(id)data{
self= [super init];
if(self) {
self.data= data;
}
return self;
}
- (NSString*)title{
return nil;
}
(UIImage*)headImage{
return nil;
}
@end</code></pre>
3.根據類創建適配器
創建適配器,繼承根適配器
@interfacePeopleAdapter :RootAdapter
@end
(instancetype)initWithData:(id)data{
self = [super init];
if( self ) {
self.data= data;
}
return self;
}
- (NSString)title{
PeopleModel model =self.data;
return model.name;
}
(UIImage)headImage{
PeopleModel model =self.data;
UIImage *image = [UIImageimageNamed:model.icon];
return image;
}</code></pre>
4.Cell中定義讀取數據方法,參數遵守AdapterProtocol協議
- (void)reloadData:(id<AdapterProtocol>)data{
self.adapterImage.image= [data headImage];
self.adapterTitle.text= [data title];
}
5.Controller中使用
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
staticNSString*identifier =@"Cell";
AdapterTableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:identifier];
if(!cell) {
cell =
[[AdapterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:identifier];
}
if(self.dataType==0) {
PeopleModel *peopleM =self.peopleDatalist[indexPath.row];
PeopleAdapter *peopleA =
[[PeopleAdapter alloc]initWithData:peopleM];
[cell reloadData:peopleA];
}else{
AnimalModel *animalM =self.animalDatalist[indexPath.row];
AnimalAdapter *animalA =
[[AnimalAdapter alloc]initWithData:animalM];
[cell reloadData:animalA];
}
return cell;
}
來自:http://www.jianshu.com/p/5044fe6419c3