前言
第一次正式的写博客,之前大学为了应付老师的差事,也有写过,但都是敷衍了事,在加上这些年都在忙着敲代码,以至于都快忘记写作了。随着工作时间越长,越是发现写博客的重要性,今天也是奋笔疾书,把我的见解分享给大家,有什么写的不对的望指正。好 ~ 进入正题。
一、何为适配器模式
在我们做项目的时候,会遇到一些相同的cell视图,但是数据源不同。比较传统的写法就是在cell中写两个Model的方法用于给视图传递值,这种方法可行,但不是最佳,如果后期其他的页面也需要用到这个cell,我们又要在cell中再写一个Model方法,不利于后期的迭代,而且代码的耦合度太高。这个时候就要用到我们的适配器了。
适配器,用于连接两种不同类的对象,使其能够协同工作。
类适配器OMT图示法(请忽略我的文字,丑的我都不想看)
二、何时使用适配器
- 已有的接口与需求不匹配
- 想要一个可复用的类,该类能够和其他不谦容的类协作
- 需要适配一个类的几个不同的子类,可以使用对象适配器适配父类的接口
三、实现
�1.协议方法
定义要适配的接口
@protocol AdapterProtocol <NSObject>
- (NSString *)title;
- (UIImage *)headImage;
@end
2.根适配器
定义被适配的数据源类,遵守AdapterProtocol协议,并重载协议方法
#import"AdapterProtocol.h"
@interface RootAdapter :NSObject<AdapterProtocol>
@property(weak,nonatomic)id data;
- (instancetype)initWithData:(id)data;
@end
@implementation RootAdapter
- (instancetype)initWithData:(id)data{
self= [super init];
if(self) {
self.data= data;
}
return self;
}
- (NSString*)title{
return nil;
}
- (UIImage*)headImage{
return nil;
}
@end
3.根据类创建适配器
创建适配器,继承根适配器
@interface PeopleAdapter :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 = [UIImage imageNamed:model.icon];
return image;
}
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{
static NSString*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;
}
项目地址:GitHub