好处:代码高聚合,方便我们管理;
编程思想:函数式响应编程;
链式编程:
CaculatorMaker.h
#import <Foundation/Foundation.h> #define ADD #define KVO @interface CaculatorMaker : NSObject @property (nonatomic, assign) KVO int result; // + - (instancetype)add:(int)num; ADD - (CaculatorMaker *(^)(int num))add; // - // * - (CaculatorMaker *(^)(int num))multy; // / @end
CaculatorMaker.m
#import "CaculatorMaker.h" @implementation CaculatorMaker //- (instancetype)add:(int)num //{ // _result += num; // return self; //} - (CaculatorMaker *(^)(int))multy { return ^(int num){ _result *= num; return self; }; } - (CaculatorMaker * (^)(int num))add { return ^(int num){ _result += num; return self; }; } @end
NSObject+Caculator.h
#import <Foundation/Foundation.h> #import "CaculatorMaker.h" @interface NSObject (Caculator) // 以后计算都使用这个方法,一调用这个方法就返回结果. + (int)makeCaculator:(void(^)(CaculatorMaker *))block; @end
NSObject+Caculator.m
#import "NSObject+Caculator.h" #import "CaculatorMaker.h" @implementation NSObject (Caculator) + (int)makeCaculator:(void (^)(CaculatorMaker *))block { // 创建计算制造者 CaculatorMaker *maker = [[CaculatorMaker alloc] init]; // 计算 block(maker); return maker.result; } @end
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // add(1).add(2) // 1.创建计算制造者 CaculatorMaker *maker = [[CaculatorMaker alloc] init]; // 10 + 20 + 30 + 40 // 链式编程思想: maker.add(10).add(20).add(30).add(40) // int result = [maker.add(10).add(20).add(30).add(40) result]; // 提供一个没参数的add方法,返回值block // int reslut = [[[[[maker add:10] add:20] add:30] add:40] result]; // block:使代码高聚合 int result = [NSObject makeCaculator:^(CaculatorMaker *maker) { // 把所有的计算代码封装到这里 maker.add(10).add(20); maker.add(30).add(40); maker.multy(3); }]; NSLog(@"%d",result); }
时间: 2024-10-11 20:26:10