用block 代替类继承实现方法的多态性重构技巧分享




源起

  以类继承方式实现方法的多态方式,在项目中发现用起来比较麻烦

 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值