标签:
第二章:商场促销——策略模式
父类CashSuper
CashSuper.h
@interface CashSuper : NSObject -(double)acceptCash:(double)money; @end
CashSuper.m
@implementation CashSuper
-(double)acceptCash:(double)money{
return money;
}
@end
正常消费类 CashNormal
CashNormal.h
#import <Foundation/Foundation.h> #import "CashSuper.h" @interface CashNormal : CashSuper @end
CashNormal.m
#import "CashNormal.h" @implementation CashNormal -(double)acceptCash:(double)money{ return money; } @end
打折消费类CashRebate
CashRebate.h
#import <Foundation/Foundation.h> #import "CashSuper.h" @interface CashRebate : CashSuper @property(assign,nonatomic)double Rebate; -(instancetype)initWithRebate:(double) Rebate; @end
CashRebate.m
#import "CashRebate.h" @implementation CashRebate - (instancetype)initWithRebate:(double)Rebate{ self = [super init]; if (self) { _Rebate=Rebate; } return self; } -(double)acceptCash:(double)money{ return money*_Rebate; } @end
返利消费类CashReturn
CashReturn.h
#import <Foundation/Foundation.h> #import "CashSuper.h" @interface CashReturn : CashSuper @property(assign,nonatomic)double moneyCondition; @property(assign,nonatomic)double moneyReturn; -(instancetype)initWithMoneyCondition:(double)moneyCondition :(double)moneyReturn; @end
CashReturn.m
#import "CashReturn.h" @implementation CashReturn -(instancetype)initWithMoneyCondition:(double)moneyCondition :(double)moneyReturn { self = [super init]; if (self) { _moneyCondition=moneyCondition; _moneyReturn=moneyReturn; } return self; } -(double)acceptCash:(double)money{ double result=money; if (money>=_moneyCondition) { result=money-((int)(money/_moneyCondition))*_moneyReturn; } return result; } @end
配置类,维护对对象的使用CashContext类
CashContext.h
#import <Foundation/Foundation.h> #import "CashSuper.h" @interface CashContext : NSObject @property(nonatomic,strong)CashSuper *cashsuper; -(instancetype)initWith:(CashSuper *)csuper; -(double)GetResult:(double)money; @end
CashContext.m
#import "CashContext.h" @implementation CashContext - (instancetype)initWith:(CashSuper *)csuper { self = [super init]; if (self) { _cashsuper=csuper; } return self; } -(double)GetResult:(double)money{ return [_cashsuper acceptCash:money]; } @end
主函数
#import <Foundation/Foundation.h> #import "CashContext.h" #import "CashSuper.h" #import "CashNormal.h" #import "CashRebate.h" #import "CashReturn.h" int main(int argc, const char * argv[]) { @autoreleasepool { char type=‘B‘; double result=0.0; CashContext *cc=nil; switch (type) { case ‘N‘: cc=[[CashContext alloc]initWith:[[CashNormal alloc]init]]; break; case ‘B‘: cc=[[CashContext alloc]initWith:[[CashRebate alloc]initWithRebate:0.7]]; break; case ‘T‘: cc=[[CashContext alloc]initWith:[[CashReturn alloc] initWithMoneyCondition:300 :100]]; break; } result = [cc GetResult:500]; NSLog(@"%f",result); } return 0; }
运行打折类
标签:
原文地址:http://www.cnblogs.com/qianLL/p/5232126.html