Strategy(策略模式)
它定義了算法家族隅肥,分別封裝起來锨咙,讓它們之間可以互相替換,此模式讓算法的變化抱慌,不會影響到使用算法的客戶。通過一個Context指定一個Strategy眨猎,通過Strategy的子類實現(xiàn)不同的算法抑进。
vc.m
HCDCashContext *context = [[HCDCashContext alloc]initWithCashType:CashTypeNormal];
NSLog(@"結(jié)果是%f",[context getResult:100]);
HCDCashContext *contextReturn = [[HCDCashContext alloc]initWithCashType:CashTypeReturn];
NSLog(@"結(jié)果是%f",[contextReturn getResult:100]);
HCDCashContext *contextRobate = [[HCDCashContext alloc]initWithCashType:CashTypeRobate];
NSLog(@"結(jié)果是%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];
}