iOS设计模式之—适配器模式

fglownarxx 7年前
   <h3>一、何为适配器模式</h3>    <p>在我们做项目的时候,会遇到一些相同的cell视图,但是数据源不同。比较传统的写法就是在cell中写两个Model的方法用于给视图传递值,这种方法可行,但不是最佳,如果后期其他的页面也需要用到这个cell,我们又要在cell中再写一个Model方法,不利于后期的迭代,而且代码的耦合度太高。这个时候就要用到我们的适配器了。</p>    <p>适配器,用于连接两种不同类的对象,使其能够协同工作。</p>    <p>类适配器OMT图示法(请忽略我的文字,丑的我都不想看)</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/fced0092e6be2410e128c413f204baf8.png"></p>    <h3>二、何时使用适配器</h3>    <ol>     <li>已有的接口与需求不匹配</li>     <li>想要一个可复用的类,该类能够和其他不谦容的类协作</li>     <li>需要适配一个类的几个不同的子类,可以使用对象适配器适配父类的接口</li>    </ol>    <h3>三、实现</h3>    <p>1.协议方法</p>    <p>定义要适配的接口</p>    <pre>  <code class="language-objectivec">@protocol AdapterProtocol <NSObject>    - (NSString *)title;  - (UIImage *)headImage;    @end</code></pre>    <p>2.根适配器</p>    <p>定义被适配的数据源类,遵守AdapterProtocol协议,并重载协议方法</p>    <pre>  <code class="language-objectivec">#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>    <p>3.根据类创建适配器</p>    <p>创建适配器,继承根适配器</p>    <pre>  <code class="language-objectivec">@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>    <p>4.Cell中定义读取数据方法,参数遵守AdapterProtocol协议</p>    <pre>  <code class="language-objectivec">- (void)reloadData:(id<AdapterProtocol>)data{    self.adapterImage.image= [data headImage];    self.adapterTitle.text= [data title];  }</code></pre>    <p>5.Controller中使用</p>    <pre>  <code class="language-objectivec">- (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;  }</code></pre>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/5044fe6419c3</p>    <p> </p>