问题引入:在一些购物系统,可能会在搞一些促销,比如满多少减多少,全场打折等,那这样的怎么设计比较好呢?这时策略模式就是一个很好的解决方法。
1.定义
定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
2.UML类图
3.实现
1、定义baseStrategy接口CashBase
#import#import @protocol CashBase -(CGFloat)acceptCash:(CGFloat)cash;@end
2.定义Strategy接口子类CashNormal
#import#import "CashBase.h"@interface CashNormal : NSObject @end
#import "CashNormal.h"@implementation CashNormal-(CGFloat)acceptCash:(CGFloat)cash{ return cash;}@end
定义子类CashRobate
#import#import "CashBase.h"@interface CashRobate : NSObject -(instancetype)initWithMoneyRebate:(CGFloat)moneyRebate;@end
#import "CashRobate.h"@interface CashRobate ()@property(nonatomic)CGFloat moneyRebate;@end@implementation CashRobate-(instancetype)initWithMoneyRebate:(CGFloat)moneyRebate{ self = [super init]; if (self) { _moneyRebate = moneyRebate; } return self;}-(CGFloat)acceptCash:(CGFloat)cash{ return self.moneyRebate * cash;}@end
定义子类CaseReturn
#import#import "CashBase.h"@interface CaseReturn : NSObject -(instancetype)initWithMoneyCondition:(CGFloat)moneyCondition moneyReturn:(CGFloat)moneyReturn;@end
#import "CaseReturn.h"@interface CaseReturn ()@property(nonatomic)CGFloat moneyCondition;@property(nonatomic)CGFloat moneyReturn;@end@implementation CaseReturn-(instancetype)initWithMoneyCondition:(CGFloat)moneyCondition moneyReturn:(CGFloat)moneyReturn{ self = [super init]; if (self) { _moneyCondition = moneyCondition; _moneyReturn = moneyReturn; } return self;}-(CGFloat)acceptCash:(CGFloat)cash{ return self.moneyCondition - self.moneyReturn;}@end
定义context
#import#import "CashBase.h"@interface CashContext : NSObject-(instancetype)initWithCashSuper:(id )cashBase;-(CGFloat)getResult:(CGFloat)money;@end
#import "CashContext.h"@interface CashContext()@property(strong,nonatomic) idcashSuper;@end@implementation CashContext-(instancetype)initWithCashSuper:(id )cashBase{ self = [super init]; if (self) { self.cashSuper = cashBase; } return self;}-(CGFloat)getResult:(CGFloat)money{ return [self.cashSuper acceptCash:money];}@end
4.调用
CashRobate *robate = [[CashRobate alloc]initWithMoneyRebate:0.8]; CashContext *context = [[CashContext alloc]initWithCashSuper:robate]; NSLog(@"结果是%f",[context getResult:100]); CaseReturn *cashReturn = [[CaseReturn alloc]initWithMoneyCondition:300 moneyReturn:100]; CashContext *contextReturn = [[CashContext alloc]initWithCashSuper:cashReturn]; NSLog(@"结果是%f",[contextReturn getResult:0]);
5.输出