Adapter(适配器模式)
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。适配器模式主要应用于“希望复用一些现存的类,但是接口又与复用环境要求不一致的情况”,在遗留代码复用、类库迁移等方面非常有用。
比如SDWebImage里面的SDWebImageOperation协议有一个cancel方法,所有实现了该协议的对象都有cancel方法,都可以取消。从而让不同类型的对象都可以通过同一个接口取消。比如SDWebImageDownloaderOperation、SDWebImageCombinedOperation这两个不同的对象都可以调用cancel接口。还有比如Weex消息和Porsche消息之间的通过Bridge来适配消息交互。android的ListView就是通过adapter来实现所有的布局和事件操作的。
VC.m
HCDPlayer *forward = [[HCDForwards alloc]initWithName:@"maidi"];
[forward attack];
[forward defense];
HCDPlayer *foreignCenter = [[HCDTranslator alloc]initWithName:@"姚明"];
[foreignCenter attack];
[foreignCenter defense];
HCDPlayer.h
@interface HCDPlayer : NSObject
@property(nonatomic,copy)NSString *name;
-(void)attack;
-(void)defense;
-(instancetype)initWithName:(NSString *)name;
@end
HCDPlayer.m
@implementation HCDPlayer
-(instancetype)initWithName:(NSString *)name{
self = [super init];
if (self) {
_name = name;
}
return self;
}
@end
HCDForwards.m
@implementation HCDForwards
-(void)attack{
NSLog(@"前锋%@进攻",self.name);
}
-(void)defense{
NSLog(@"前锋%@防守",self.name);
}
@end
HCDTranslator.h
@interface HCDTranslator : HCDPlayer
@property(nonatomic,strong)HCDForeignCenter *foreigncenter;
@end
HCDTranslator.m
@implementation HCDTranslator
-(instancetype)initWithName:(NSString *)name{
self = [super init];
if (self) {
_foreigncenter = [[HCDForeignCenter alloc]initWithName:name];
}
return self;
}
-(void)defense{
[self.foreigncenter foreignDefent];
}
-(void)attack{
[self.foreigncenter foreignAttact];
}
@end