链式编程思想:把要做的事情封装到block,给外界提供一个返回这个Block的方法
链式编程思想方法特点:方法返回值必须是block,block参数:放需要操作的内容,block返回值:方法调用者
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CaculatorMaker : NSObject
@property (nonatomic, assign) int result;
// +
- (CaculatorMaker *(^)(CGFloat num))add;
// -
- (CaculatorMaker *(^)(CGFloat num))subtract;
// *
- (CaculatorMaker *(^)(CGFloat num))multy;
// ÷
- (CaculatorMaker *(^)(CGFloat num))divide;
#import "CaculatorMaker.h"
@implementation CaculatorMaker
- (CaculatorMaker * (^)(CGFloat num))add
{
return ^(CGFloat num){
_result += num;
return self;
};
}
- (CaculatorMaker *(^)(CGFloat))subtract
{
return ^(CGFloat num){
_result -= num;
return self;
};
}
- (CaculatorMaker *(^)(CGFloat))multy
{
return ^(CGFloat num){
_result *= num;
return self;
};
}
- (CaculatorMaker *(^)(CGFloat))divide
{
return ^(CGFloat num){
_result = _result/num;
return self;
};
}
@end
#import <Foundation/Foundation.h>
#import "CaculatorMaker.h"
@interface NSObject (Caculator)
// 以后计算都使用这个方法,一调用这个方法就返回结果.
+ (CGFloat)makeCaculator:(void(^)(CaculatorMaker *))block;
@end
#import "NSObject+Caculator.h"
#import "CaculatorMaker.h"
@implementation NSObject (Caculator)
+ (CGFloat)makeCaculator:(void (^)(CaculatorMaker *))block
{
// 创建计算制造者
CaculatorMaker *maker = [[CaculatorMaker alloc] init];
// 计算
block(maker);
return maker.result;
}
@end
调用
#import "ViewController.h"
#import "CaculatorMaker.h"
#import "NSObject+Caculator.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// block:使代码高聚合
CGFloat result = [NSObject makeCaculator:^(CaculatorMaker *maker) {
// 把所有的计算代码封装到这里
maker.add(10).add(20);
maker.add(30).add(40);
maker.multy(3);
maker.divide(10);
}];
NSLog(@"%.2f",result);
}