源起
以类继承方式实现方法的多态方式,在项目中发现用起来比较麻烦
1. 文件量增加了,每一个多态个体需要两个文件来承载,一个.h一个.m,造成项目中文件量大增,增加代码管理维护成本。
2. 在每次使用时,需要写很多代码,开发速度受到影响,不断重构,提高代码复用,持续降低开发成本是目标。
实现方式
增加一个目标类的子类以实现block化,在需要实现多态的方法处回调block
例子
.h
@interface ModelStatusInfoB : ModelStatusInfo
@property(nonatomic,strong)NSString * (^titleForEmptyBlock)(void);
@property(nonatomic,strong)NSString * (^subTitleForEmptyBlock)(void);
@property(nonatomic,strong)NSString * (^titleForErrorBlock)(NSError *error);
@property(nonatomic,strong)NSString * (^subTitleForErrorBlock)(NSError *error);
@property(nonatomic,strong)NSString * (^actionButtonTitleForEmptyBlock)(void);
@property(nonatomic,strong)NSString * (^actionButtonTitleForErrorBlock)(NSError *error);
@property(nonatomic,strong)UIImage * (^imageForEmptyBlock)();
@property(nonatomic,strong)UIImage * (^imageForErrorBlock)(NSError *error);
.m
@implementation ModelStatusInfoB
- (NSString *)titleForEmpty {
returnself.titleForEmptyBlock();
}
- (NSString *)subTitleForEmpty {
returnself.subTitleForEmptyBlock();
}
- (NSString *)actionButtonTitleForEmpty {
returnself.actionButtonTitleForEmptyBlock();
}
- (NSString *)titleForError:(NSError *)error {
returnself.titleForErrorBlock(error);
}
- (NSString *)subTitleForError:(NSError *)error {
returnself.subTitleForErrorBlock(error);
}
- (NSString *)actionButtonTitleForError:(NSError *)error {
returnself.actionButtonTitleForErrorBlock(error);
}
- (UIImage *)imageForEmpty {
returnself.imageForEmptyBlock();
}
- (UIImage *)imageForError:(NSError *)error {
returnself.imageForErrorBlock(error);
}
client
@implementation ModelStatusHandler (Factory)
+(ModelStatusHandler *)searchListFailedStatusHandler{
TBModelStatusInfoB *info = [[TBModelStatusInfoBalloc] init];
info.titleForEmptyBlock=^{
return @"没有搜索结果";
};
info.subTitleForEmptyBlock=^{
return@"没有找到相关的宝贝,先去看看热门搜索吧";
};
info.actionButtonTitleForEmptyBlock=^{
return @"";
};
info.imageForEmptyBlock=^{
return [UIImageimageNamed:@"searchicon"];
};
info.titleForErrorBlock=^(NSError *error){
return @"数据加载失败";
};
info.subTitleForErrorBlock=^(NSError *error){
return@"请检查您的是否联网,点击按钮重新加载";
};
info.actionButtonTitleForErrorBlock=^(NSError *error){
return @"重新加载";
};
info.imageForErrorBlock=^(NSError *error){
return [UIImageimageWithContentsOfFile:TBPath(@"wifi")];
};
ModelStatusHandler *handler = [[ModelStatusHandleralloc] initWithStatusInfo:info];
return handler;
}