您的位置:首页 > 移动开发 > IOS开发

iOS设计模式——适配器

2017-01-03 10:55 260 查看
一  目的:

   为了让客户端尽可能的通用,使用适配器模式来隔离客户端与外部参数的联系,只让客户端与适配器通信.

   适配器对复杂子页面或多种cell的数据展示有很好的优势。

二  原理:

    1.将网络请求下来的数据转换为模型后,放入适配器中

    2.适配器对数据处理(比如高度计算)和选用对应的cell类型

    3.页面数据的展示从适配器中获取模型

    (这些原理在第四步的实际代码应用中会更好理解)

三  适配器类

     .h代码

    
@interface CellDataAdapter : NSObject

/**
*  Cell's reused identifier.
*/
@property (nonatomic, strong) NSString     *cellReuseIdentifier;

/**
*  Data, can be nil.
*/
@property (nonatomic, strong) id            data;

/**
*  Cell's height.
*/
@property (nonatomic)         CGFloat       cellHeight;

/**
*  Cell's type (The same cell, but maybe have different types).
*/
@property (nonatomic)         NSInteger     cellType;

/**
*  CellDataAdapter's convenient method.
*
*  @param cellReuseIdentifiers Cell's reused identifier.
*  @param data                 Data, can be nil.
*  @param cellHeight           Cell's height.
*  @param cellType             Cell's type (The same cell, but maybe have different types).
*
*  @return CellDataAdapter's object.
*/
+ (instancetype)cellDataAdapterWithCellReuseIdentifier:(NSString *)cellReuseIdentifiers
data:(id)data
cellHeight:(CGFloat)cellHeight
cellType:(NSInteger)cellType;

#pragma mark - Optional properties.

/**
*  The tableView.
*/
@property (nonatomic, weak)   UITableView  *tableView;

/**
*  TableView's indexPath.
*/
@property (nonatomic, weak)   NSIndexPath  *indexPath;


.m代码

#import "CellDataAdapter.h"

@implementation CellDataAdapter

+ (CellDataAdapter *)cellDataAdapterWithCellReuseIdentifier:(NSString *)cellReuseIdentifiers
data:(id)data
cellHeight:(CGFloat)cellHeight
cellType:(NSInteger)cellType {

CellDataAdapter *adapter    = [[self class] new];
adapter.cellReuseIdentifier = cellReuseIdentifiers;
adapter.data                = data;
adapter.cellHeight          = cellHeight;
adapter.cellType            = cellType;

return adapter;
}

@end


四   实际代码应用参考

 

  4.1 控制器导入 #import"CellDataAdapter.h"
 
  4.2 将网络请求后的模型数据放到放到一个方法里处理成适配器
     (dataArray放的是适配器不是模型)
    4.2.1 传入模型数据

   [self.tableDataArrayaddObject:[selfvtNewsModelCellAdapter:self.vtNewsModel]];
    4.2.2 处理成适配器

- (CellDataAdapter *)vtNewsModelCellAdapter:(id)data {
    return [CellDataAdaptercellDataAdapterWithCellReuseIdentifier:@"vtNewsModelCell"data:data
  cellHeight:0cellType:0];
}

   5. tableview 代理方法中将适配器传给cell。
 (cell包含适配器属性 :
 
 @property (nonatomic, weak) CellDataAdapter  
      *dataAdapter;)

     customCell.dataAdapter = dataAdapter;

   6. cell加载需要的数据模型从适配器获取
    (其他信息比如有高度值,cell类型等,从适配器中获取)

     VtNewsModel *model      =self.dataAdapter.data;

   
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: