iOS适配器设计模式
其实就是对某个控件上的各个部分,用一个model来统一赋值,而在实际中可能遇到不同的model要赋值到这个控件上,那我们先将那些model转为控件的model。而那个控件的model其实就是适配器ModelAdapter。
比如某个控件是用来设置title和image的。那么这个适配器就应该有title和image属性。
如果我们的model1和model2都还未定义title和image,则我们可以使用协议来定义model1和model2,
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@protocol ContentViewAdapterProtocol <NSObject> {
}
- (UIImage*)image;
- (NSString*)title;
@end
#import <Foundation/Foundation.h>
#import "ContentViewAdapterProtocol.h"
@interface ContentViewAdapter : NSObject<ContentViewAdapterProtocol> {
}
@property (nonatomic, weak, readonly) id model;
- (instancetype)initWithModel:(id)model;
@end
适配器:直接使用对象适配器
//对象适配器:对象适配器的好处是在一个类里处理不同的数据
#import "ContentViewModelAdapter.h"
#import "Model1.h"
#import "Model2.h"
@implementation ContentViewModelAdapter
- (instancetype)initWithModel:(id)model {
self = [super init];
if (self) {
_ model = model;
}
return self;
}
- (UIImage *)image {
UIImage *image = nil;
if ([self. model isMemberOfClass:[Model1 class]]) {
Model1 *model = self.model;
image = [UIImage imageNamed:model.imageName];
} else {
Model2 *model = self.model;
image = model.image;
}
return image;
}
- (NSString *)title {
NSString *title = nil;
if ([self.model isMemberOfClass:[Model1 class]]) {
Model1 *model = self.model;
title = model.title;
} else {
Model2 *model = self.model;
title = model.title;
}
return title;
}
方法二:使用类适配器
#import "ContentViewModelAdapter.h"
@interface Model1Adeapter : ContentViewModelAdapter
@end
@interface Model2Adeapter : ContentViewModelAdapter
@end