行为型之九-策略模式

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];
}

设计图

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容