iOS必备设计模式-责任链

2019-05-07  本文已影响0人  MR_詹

设计模式-责任链

作用:

实现:

实例:

image.png
创建基础的链对象

#import <Foundation/Foundation.h>


@class BusinessObject;
typedef void (^CompletionBlock)(BOOL handled);
typedef void (^ResultBlock)(BusinessObject *handler,BOOL handled);


@interface BusinessObject : NSObject
/* 下一个响应者(响应链构成的关键) **/
@property (nonatomic, strong, readwrite) BusinessObject *nextBusiness;

/* 响应者的处理方法 **/
- (void)handle:(ResultBlock)result;
/* 各个业务在该方法当中做实际业务处理 **/
- (void)handleBusiness:(CompletionBlock)completion;


@end
#import "BusinessObject.h"

@implementation BusinessObject

/* 响应者的处理方法 **/
- (void)handle:(ResultBlock)result
{
    CompletionBlock completion = ^(BOOL handled) {
        // 当前业务处理掉,上抛结果
        if (handled) {
            result(self,handled);
        }
        else{
            // 沿着责任链,指派给下一个业务处理
            if (self.nextBusiness) {
                [self.nextBusiness handle:result];
            }
            else{
                // 没有业务处理,上抛
                result(nil,NO);
            }
        }
    };
    
    // 当前业务请求
    [self handleBusiness:completion];
}


/* 各个业务在该方法当中做实际业务处理 **/
- (void)handleBusiness:(CompletionBlock)completion
{
    /*
        业务逻辑处理
        如网络请求、本地照片查询等
     */
}

@end
新建三个类,都继承于基础类BusinessObject,并重写handleBusiness方法,实现对应的业务

#import "BusinessObject.h"

NS_ASSUME_NONNULL_BEGIN

@interface BusinessObjectA : BusinessObject

@end

NS_ASSUME_NONNULL_END


#import "BusinessObjectA.h"

@implementation BusinessObjectA


- (void)handleBusiness:(CompletionBlock)completion {
    NSLog(@"执行A业务");
    completion(NO);
}


@end

修改前的业务流:a-b-c


image.png

修改后的业务流:c-b-a


image.png
上一篇 下一篇

猜你喜欢

热点阅读