Strategy(策略模式)
它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。通过一个Context指定一个Strategy,通过Strategy的子类实现不同的算法。
vc.m
HCDCashContext *context = [[HCDCashContext alloc]initWithCashType:CashTypeNormal];
NSLog(@"结果是%f",[context getResult:100]);
HCDCashContext *contextReturn = [[HCDCashContext alloc]initWithCashType:CashTypeReturn];
NSLog(@"结果是%f",[contextReturn getResult:100]);
HCDCashContext *contextRobate = [[HCDCashContext alloc]initWithCashType:CashTypeRobate];
NSLog(@"结果是%f",[contextRobate getResult:100]);
HCDCashContext.h
-(instancetype)initWithCashSuper:(id<HCDCashBase>)cashBase;
-(instancetype)initWithCashType:(HCDCashType)type;
-(CGFloat)getResult:(CGFloat)money;
HCDCashContext.m
-(instancetype)initWithCashSuper:(id<HCDCashBase>)cashBase{
self = [super init];
if (self) {
self.cashSuper = cashBase;
}
return self;
}
-(instancetype)initWithCashType:(HCDCashType)type{
self = [super init];
if (self) {
if (type == CashTypeNormal) {
self.cashSuper = [[HCDCashNormal alloc]init];
}else if(type == CashTypeRobate){
self.cashSuper = [[HCDCashRobate alloc]initWithMoneyRebate:0.8];
}else if(type == CashTypeReturn){
self.cashSuper = [[HCDCaseReturn alloc]initWithMoneyReturn:5];
}
}
return self;
}
-(CGFloat)getResult:(CGFloat)money{
return [self.cashSuper acceptCash:money];
}
网友评论