本文介紹了適配器模式的定義和概念液南,以及實際開發(fā)中的場景和案例壳猜,對應(yīng)的代碼可以在AdapterPatternDemo這里下載到。
1. 定義
什么是適配器模式滑凉?(電源適配器统扳、轉(zhuǎn)接頭)
特點:
- 將一個原始接口轉(zhuǎn)成客戶端需要的接口
- 原始接口不兼容現(xiàn)在新的接口,將它們兩個接口一起工作需要適配器解決
2. 應(yīng)用場景
- 接口不兼容(適配器模式)
- 可以重復(fù)使用的類畅姊,用于與一些彼此之間沒有太大關(guān)聯(lián)的一些類一起工作(適配器模式)
- 統(tǒng)一輸出接口咒钟,輸入的類型無法確定(適配器模式)
3. 角色劃分
- 第一個角色:適配器(最核心關(guān)鍵角色)
- 第二個角色:目標接口
- 第三個角色:被適配類(角色)
- 第四個角色:客戶端
4. 案例
4.1 案例說明
將美元(被適配對象—>Adaptee)——>人民幣(目標接口——>Target)
適配器將美元轉(zhuǎn)成人民幣(Adaper)
4.2 定義Target協(xié)議
#import <Foundation/Foundation.h>
@protocol TargetProtocal <NSObject>
- (NSInteger)getCNY;
@end
4.3 定義被適配的對象類Adaptee
// USDAdaptee.h
#import <Foundation/Foundation.h>
@interface USDAdaptee : NSObject
- (void)setUSD:(NSInteger)usd;
- (NSInteger)getUSD;
@end
// USDAdaptee.m
#import "USDAdaptee.h"
@interface USDAdaptee ()
@property (nonatomic, assign) NSInteger usd;
@end
@implementation USDAdaptee
- (void)setUSD:(NSInteger)usd {
_usd = usd;
}
- (NSInteger)getUSD {
return _usd;
}
@end
4.4 使用對象適配器
對象適配器使用的是組合的模式,適配器類實現(xiàn)Target協(xié)議若未,并且在適配器類中定義一個Adaptee的屬性朱嘴,重寫協(xié)議返回對Adaptee屬性對象做相應(yīng)的轉(zhuǎn)換操作,來達到讓Adaptee適配Target的目的陨瘩。
// CNYObjectAdapter.h
#import <Foundation/Foundation.h>
#import "USDAdaptee.h"
#import "TargetProtocal.h"
@interface CNYObjectAdapter : NSObject <TargetProtocal>
@property (nonatomic, strong) USDAdaptee* usd;
- (instancetype)initWithUSD:(USDAdaptee*)usd;
@end
// CNYObjectAdapter.m
#import "CNYObjectAdapter.h"
@implementation CNYObjectAdapter
- (instancetype)initWithUSD:(USDAdaptee*)usd {
self = [super init];
if (self) {
_usd = usd;
}
return self;
}
- (NSInteger)getCNY {
return _usd.getUSD * 6.8;
}
@end
4.5 使用類適配器
類適配器使用的是繼承的模式腕够,適配器類實現(xiàn)Target
協(xié)議,并且該適配器類繼承Adaptee
類舌劳,在重寫的Target
協(xié)議方法中使用super
調(diào)用Adaptee
的方法做相應(yīng)的轉(zhuǎn)換操作,來達到讓Adaptee
適配Target
的目的玫荣。
// CNYClassAdapter.h
#import <Foundation/Foundation.h>
#import "USDAdaptee.h"
#import "TargetProtocal.h"
@interface CNYClassAdapter : USDAdaptee <TargetProtocal>
@end
// CNYClassAdapter.m
#import "CNYClassAdapter.h"
@implementation CNYClassAdapter
- (NSInteger)getCNY {
return [self getUSD] * 6.8;
}
@end
4.6 客戶端使用
// 類適配器的使用
CNYClassAdapter* cnyClsAdapter = [CNYClassAdapter new];
[cnyClsAdapter setUSD:1000];
NSInteger cny = [cnyClsAdapter getCNY];
NSLog(@"CNYClassAdapter ==> cny = %@", @(cny));
// 對象適配器的使用
USDAdaptee* usd = [USDAdaptee new];
[usd setUSD:1000];
CNYObjectAdapter* cnyObjAdapter = [[CNYObjectAdapter alloc] initWithUSD:usd];
NSInteger cny2 = [cnyObjAdapter getCNY];
NSLog(@"CNYClassAdapter ==> cny = %@", @(cny2));
// 結(jié)果輸出
// CNYClassAdapter ==> cny = 6800
// CNYClassAdapter ==> cny = 6800
5. 真實開發(fā)案例
真實的開發(fā)案例中甚淡,會從一般的開發(fā)步驟說起,首先對一般的場景代碼進行重構(gòu)捅厂,把列表UITableVIewDataSource/UITableViewDelegate獨立為一個簡單的適配器贯卦;然后在此基礎(chǔ)上進行抽象和擴展,構(gòu)建一個更加靈活和易擴展的復(fù)雜列表適配器焙贷。
5.1 一般的開發(fā)步驟
一般的撵割,在做一個列表的展示數(shù)據(jù)的時候,我們習(xí)慣的把創(chuàng)建列表辙芍、創(chuàng)建列表數(shù)據(jù)啡彬、注冊列表的cell、實現(xiàn)列表的UITableVIewDataSource/UITableViewDelegate方法等步驟放在ViewController來完成故硅,類似如下的代碼庶灿,這種方法在簡單的列表中看不出弊端,如果這個ViewController中添加了其他更多的邏輯吃衅、代碼往踢、這個類就顯得十分龐大了;此外其他的頁面有用到這個一樣的列表只是數(shù)據(jù)不同徘层,那么還得重新去實現(xiàn)這個步驟峻呕,列表的這部分邏輯不能夠復(fù)用利职,產(chǎn)生了冗余的代碼,don't repeat yourself瘦癌,這很糟糕眼耀,所以很有必要重構(gòu)這段代碼,讓他能夠很好的進行復(fù)用佩憾,使用適配器模式就能夠很好的做到這點哮伟。下面會講到一個簡單點的適配器和一個復(fù)雜點的適配器,來重構(gòu)我們的代碼妄帘。
@implementation SimpleViewController
- (void)viewDidLoad {
// 處理UI和數(shù)據(jù)的步驟省略....
// retister cell
[self.tableView registerClass:[GameCell class] forCellReuseIdentifier:NSStringFromClass([GameCell class])];
}
#pragma mark - ......::::::: UITableViewDelegate :::::::......
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
GameCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GameCell class])];
GameModel* gameModel = _datas[indexPath.row];
[cell loadData:gameModel indexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
}
@end
5.2 簡單的列表適配器
簡單的列表適配器就是把和UITableVIewDataSource/UITableViewDelegate相關(guān)的代碼獨立出來楞黄,來減輕ViewController,實現(xiàn)起來也很簡單:
// SimpleAdapter.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface SimpleAdapter : NSObject <UITableViewDelegate, UITableViewDataSource>
- (instancetype)initWithTableView:(UITableView*)tableView datas:(NSMutableArray*)datas;
@end
// SimpleAdapter.m
#import "SimpleAdapter.h"
#import "GameCell.h"
#import "GameModel.h"
@interface SimpleAdapter ()
@property (nonatomic, strong) NSMutableArray* datas;
@end
@implementation SimpleAdapter
- (instancetype)initWithTableView:(UITableView*)tableView datas:(NSMutableArray*)datas {
self = [super init];
if (self) {
// retister cell
[tableView registerClass:[GameCell class] forCellReuseIdentifier:NSStringFromClass([GameCell class])];
_datas = datas;
}
return self;
}
- (void)dealloc {
NSLog(@"=====SimpleAdapter dealloc=====");
}
#pragma mark - ......::::::: UITableViewDelegate :::::::......
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
GameCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GameCell class])];
GameModel* gameModel = _datas[indexPath.row];
[cell loadData:gameModel indexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
}
@end
5.3 簡單列表適配器的使用
簡單列表適配器的使用十分的簡單抡驼,把TableVIew的delegate和DataSource設(shè)置為Adapter對象就行了鬼廓,并且列表的適配器復(fù)用也變得十分的方便了,當然使用這種方法在一些復(fù)雜的場景就不那么適用了致盟,下面會在簡單列表適配器的基礎(chǔ)上進行擴展碎税,也就是復(fù)雜的列表適配器,適用于更復(fù)雜的更一般性的場景馏锡,并且具有良好的擴張性雷蹂。
@implementation SimpleAdapterViewController
- (void)viewDidLoad {
// 處理UI和數(shù)據(jù)的步驟省略....
self.adapter = [[SimpleAdapter alloc] initWithTableView:self.tableView datas:datas];
self.tableView.dataSource = self.adapter;
self.tableView.delegate = self.adapter;
}
@end
5.4 復(fù)雜的列表適配器
5.4.1 復(fù)雜的列表適配器層級分析
復(fù)雜列表適配器分為三個層
- Cell適配器層
- Section適配器層
- List列表適配器層
這三個層可以是獨立的存在,同時地底層也可以作為高層的依賴杯道,使用組合的方式實現(xiàn)擴展匪煌。
對應(yīng)的創(chuàng)建三個層的協(xié)議:
// Cell適配器層->CellAdapterProtocal
@protocol CellAdapterProtocal <NSObject, UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
@end
// Section適配器層->SectionAdapterProtocal
@protocol SectionAdapterProtocal <NSObject, UITableViewDelegate, UITableViewDataSource>
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
@end
// List列表適配器層->ListAdapterProtocal
@protocol ListAdapterProtocal <NSObject, SectionAdapterProtocal, CellAdapterProtocal>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
@end
5.4.2 對應(yīng)層的Base實現(xiàn)
對應(yīng)層需要做一個Base的實現(xiàn),目的是為了把通用的工作放在Base實現(xiàn)類中党巾,把差異的工作放到子類中萎庭,這樣達到復(fù)用代碼和減少實現(xiàn)代碼的目的。
- Cell適配器層的Base實現(xiàn)
@implementation BaseCellAdapter
- (instancetype)initWithTableView:(UITableView*)tableView datas:(NSMutableArray*)datas {
self = [super init];
if (self) {
// retister cell
for (Class claz in [self registerCellClasses]) {
[tableView registerClass:claz forCellReuseIdentifier:NSStringFromClass(claz)];
}
_datas = datas;
}
return self;
}
#pragma mark - ......::::::: UITableViewDelegate :::::::......
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.datas.count;
}
#pragma mark - ......::::::: override :::::::......
- (NSArray*)registerCellClasses {
return nil;
}
@end
- Section適配器層的Base實現(xiàn)
Section適配器層除了做了和列表Section展示有關(guān)的工作齿拂,還負責(zé)做Cell展示相關(guān)的工作驳规,所以Section適配器層依賴了Cell適配器層,需要把Cell適配器層用到的內(nèi)容轉(zhuǎn)發(fā)給Cell適配器層署海,轉(zhuǎn)發(fā)這部分使用了OC中的轉(zhuǎn)發(fā)來減少代碼量吗购,使用的的方法為respondsToSelector
和forwardingTargetForSelector
,具體可以看下面的代碼叹侄。
// BaseSectionAdapter.h
@interface BaseSectionAdapter : NSObject <SectionAdapterProtocal, CellAdapterProtocal>
@property (nonatomic, strong) NSString* sectionTitle;
@property (nonatomic, assign) NSInteger sectionHeight;
@property (nonatomic, strong) id<CellAdapterProtocal> cellAdapter;
- (instancetype)initWithCellAdapter:(id<CellAdapterProtocal>)cellAdapter sectionTitle:(NSString*)sectionTitle sectionHeight:(NSInteger)sectionHeight;
@end
// BaseSectionAdapter.m
@implementation BaseSectionAdapter
- (instancetype)initWithCellAdapter:(id<CellAdapterProtocal>)cellAdapter sectionTitle:(NSString*)sectionTitle sectionHeight:(NSInteger)sectionHeight {
self = [super init];
if (self) {
_cellAdapter = cellAdapter;
_sectionTitle = sectionTitle;
_sectionHeight = sectionHeight;
}
return self;
}
#pragma mark - ......::::::: Section Handler :::::::......
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return self.sectionHeight;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.sectionTitle;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
return nil;
}
#pragma mark - ......::::::: Cell Handler :::::::......
#pragma mark 使用事件轉(zhuǎn)發(fā)處理Cell
- (BOOL)respondsToSelector:(SEL)aSelector
{
BOOL responds = [super respondsToSelector:aSelector];
if (!responds && self.cellAdapter != self) {
responds = [self.cellAdapter respondsToSelector:aSelector];
}
return responds;
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([self.cellAdapter respondsToSelector:aSelector]) {
return self.cellAdapter;
}
return self;
}
@end
- List列表適配器層的Base實現(xiàn)
List列表適配器層主要是做一個整合的實現(xiàn)巩搏,需要把對應(yīng)的事件轉(zhuǎn)發(fā)給對應(yīng)的Section適配器層,Section適配器層再負責(zé)把對應(yīng)的事件轉(zhuǎn)發(fā)給Cell適配器層趾代。
// BaseListAdapter.h
@interface BaseListAdapter : NSObject <ListAdapterProtocal>
@property (nonatomic, strong) NSMutableArray<id<SectionAdapterProtocal>>* sections;
@end
// BaseListAdapter.m
@implementation BaseListAdapter
#pragma mark - ......::::::: Section Handler :::::::......
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.sections.count;
}
#pragma mark - ......::::::: Section Handler :::::::......
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
id<SectionAdapterProtocal> sectionAdapter = self.sections[section];
return [sectionAdapter tableView:tableView heightForHeaderInSection:section];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id<SectionAdapterProtocal> sectionAdapter = self.sections[section];
return [sectionAdapter tableView:tableView titleForHeaderInSection:section];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
id<SectionAdapterProtocal> sectionAdapter = self.sections[section];
return [sectionAdapter tableView:tableView viewForHeaderInSection:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
id<SectionAdapterProtocal> sectionAdapter = self.sections[section];
return [sectionAdapter tableView:tableView heightForFooterInSection:section];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
id<SectionAdapterProtocal> sectionAdapter = self.sections[section];
return [sectionAdapter tableView:tableView viewForFooterInSection:section];
}
#pragma mark - ......::::::: Cell Handler :::::::......
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id<SectionAdapterProtocal> cellAdapter = self.sections[section];
return [cellAdapter tableView:tableView numberOfRowsInSection:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id<SectionAdapterProtocal> cellAdapter = self.sections[indexPath.section];
return [cellAdapter tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
id<SectionAdapterProtocal> cellAdapter = self.sections[indexPath.section];
return [cellAdapter tableView:tableView didSelectRowAtIndexPath:indexPath];
}
@end
5.4.3 具體的適配器
- 具體的Cell適配器
@implementation GameCellAdapter
#pragma mark - ......::::::: UITableViewDelegate :::::::......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
GameCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GameCell class])];
GameModel* gameModel = self.datas[indexPath.row];
[cell loadData:gameModel indexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
}
#pragma mark - ......::::::: override :::::::......
- (NSArray*)registerCellClasses {
return @[[GameCell class]];
}
@end
- 具體的Section適配器
簡單的定義了一個GameSectionAdapter繼承了BaseSectionAdapter贯底,沒有更多的擴展,實際情況可以在這邊添加更多自定義功能的代碼,來擴展Section的功能禽捆。
@interface GameSectionAdapter : BaseSectionAdapter
@end
@implementation GameSectionAdapter
@end
- 具體的List適配器
和GameSectionAdapter一樣笙什,List適配器一般是比較固定的,一般的可以直接使用BaseListAdapter來完成對應(yīng)的工作胚想,無需額外的工作琐凭,這里作為Demo還是簡單的繼承BaseListAdapter實現(xiàn)一個自定義的List適配器,這里可以直接使用BaseListAdapter達到相同的效果浊服。
@interface GameDetailListAdapter : BaseListAdapter
@end
@implementation GameDetailListAdapter
@end
5.4.4 復(fù)雜適配器的使用
復(fù)雜適配器需要創(chuàng)建CellAdapter
對象统屈、SectionAdapter
對象、ListAdapter
對象牙躺,進行組合愁憔,最后用ListAdapter
對象作為列表的delegate和dataSource。
@implementation SectionAdapterViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 處理UI和數(shù)據(jù)的步驟省略....
GameCellAdapter* cellAdapter = [[GameCellAdapter alloc] initWithTableView:self.tableView datas:datas];
GameSectionAdapter* fpsSectionAdapter = [[GameSectionAdapter alloc] initWithCellAdapter:cellAdapter sectionTitle:@"FPS Games" sectionHeight:60];
GameSectionAdapter* roleSectionAdapter = [[GameSectionAdapter alloc] initWithCellAdapter:cellAdapter sectionTitle:@"Role Play Games" sectionHeight:60];
self.adapter = [[GameDetailListAdapter alloc] init];
self.adapter.sections = [@[fpsSectionAdapter, roleSectionAdapter] mutableCopy];
self.tableView.dataSource = self.adapter;
self.tableView.delegate = self.adapter;
}
@end
實現(xiàn)的效果如下圖:
6. UML分析
7. Demo
本文的Demo可以在AdapterPatternDemo這里下載到