链式编程01
是将多个操作(多行代码)通过点号(.)链接在一起成为一句代码,使代码可读性好。a(1).b(2).c(3)
链式编程特点:方法的返回值是block,block必须有返回值(本身对象),block参数(需要操作的值)
代表:masonry框架。
@interface Caculator : NSObject
@property (nonatomic, assign) NSInteger result;
@property (nonatomic, assign) BOOL isEqule;
/**加法**/
- (Caculator *(^)(int index))add;
/**减法**/
- (Caculator *(^)(int index))reduction;
/**乘法**/
- (Caculator *(^)(int index))multiplication;
/**除法**/
- (Caculator *(^)(int index))division;
/**等于**/
- (Caculator *(^)(int index))equle;
@end
@implementation Caculator
/**加法**/
- (Caculator *(^)(int index))add
{
return ^Caculator *(int index){
self.result += index;
return self;
};
}
/**减法**/
- (Caculator *(^)(int index))reduction
{
return ^Caculator *(int index){
self.result -= index;
return self;
};
}
/**乘法**/
- (Caculator *(^)(int index))multiplication
{
return ^Caculator *(int index){
self.result *= index;
return self;
};
}
/**除法**/
- (Caculator *(^)(int index))division
{
return ^Caculator *(int index){
self.result /= index;
return self;
};
}
- (Caculator *(^)(int index))equle
{
return ^Caculator *(int index){
self.isEqule = index == self.result;
return self;
};
}
函数式编程01
是把操作尽量写成一系列嵌套的函数或者方法调用。
函数式编程特点:每个方法必须有返回值(本身对象),把函数或者Block当做参数,block参数(需要操作的值)block返回值(操作结果)
代表:ReactiveCocoa。
@interface CaculatorFunction : NSObject
@property (nonatomic, assign) int result;
@property (nonatomic, assign) BOOL isEqule;
- (CaculatorFunction *)caculatorFunction:(int (^)(int result))caculator;
- (CaculatorFunction *)equle:(BOOL (^)(int result))opertion;
@end
@implementation CaculatorFunction
- (CaculatorFunction *)caculatorFunction:(int (^)(int result))caculator
{
self.result = caculator(self.result);
return self;
}
- (CaculatorFunction *)equle:(BOOL (^)(int result))opertion
{
self.isEqule = opertion(self.result);
return self;
}
@end
使用
- (void)caculator
{
NSInteger result = [NSObject makerCaculators:^(Caculator *caculator) {
caculator.add(10).reduction(5).multiplication(3).division(5);
BOOL isEqule = caculator.multiplication(10).equle(300).isEqule;
NSLog(@"---------%ld",(long)isEqule);
}];
NSLog(@"---------%ld",(long)result);
}
- (void)caculatorFunction
{
CaculatorFunction *caculatorFunction = [[CaculatorFunction alloc] init];
BOOL isEqule = [[caculatorFunction caculatorFunction:^int(int result) {
result += 10;
result += 10;
result += 10;
NSLog(@"---------%ld",(long)result);
return result;
}] equle:^BOOL(int result) {
return result == 30;
}];
NSLog(@"---------%ld",(long)isEqule);
}