链式编程学习思考

链式编程:是将多个操作(多行代码)通过点号(.)链接在一起成为一句代码,使代码可读性好。a(1).b(2).c(3)

特点:方法的返回值是block,block必须有返回值(本身对象),block参数(需要操作的值)

例:masonry

相关代码实现:

@class CalculterModel;

#import

typedef CalculterModel *(^CalculateOption) (int);

@interface CalculterModel : NSObject

@property (nonatomic, assign) int result;

@property (nonatomic, copy) CalculateOption add;

@property (nonatomic, copy) CalculateOption sub;

@property (nonatomic, copy) CalculateOption muilt;

@property (nonatomic, copy) CalculateOption divide;

@end

#import "CalculterModel.h"

@implementation CalculterModel

//加

-(CalculateOption)add

{

            return ^(int inputNum) {

                                    self.result+=inputNum;

                return self;

            };

}

//减

-(CalculateOption)sub

{

                return ^(int inputNum){

                            self.result-=inputNum;

                return self;

                };

}

//乘

-(CalculateOption)muilt

{

            return ^(int inputNum){

                      self.result*=inputNum;

                        return self;

            };

}

//除

-(CalculateOption)divide

{

             return ^(int inputNum){

                    self.result/=inputNum;

              return self;

            };

}

实现的调用:

            CalculterModel *model = [CalculterModel new];

            int result = model.add(123).add(222).result;

            NSLog(@"result = %d",result);


你可能感兴趣的:(链式编程学习思考)