美文网首页
行为型之九-策略模式

行为型之九-策略模式

作者: iOS_肖晨 | 来源:发表于2017-09-29 11:37 被阅读11次

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

    设计图

    相关文章

      网友评论

          本文标题:行为型之九-策略模式

          本文链接:https://www.haomeiwen.com/subject/dcfiextx.html