
//Strategy
@protocol Strategy <NSObject>
- (NSInteger)doOperation:(NSInteger)a b:(NSInteger)b;
@end
//ConcreteStrategy
@interface AddStrategy : NSObject <Strategy>
@end
@implementation AddStrategy
- (NSInteger)doOperation:(NSInteger)a b:(NSInteger)b {
return a + b;
}
@end
//ConcreteStrategy
@interface SubstractStrategy : NSObject <Strategy>
@end
@implementation SubstractStrategy
- (NSInteger)doOperation:(NSInteger)a b:(NSInteger)b {
return a - b;
}
@end
//Context
@interface Calc : NSObject
@property (nonatomic, strong) id<Strategy> strategy;
- (NSInteger)execute:(NSInteger)a b:(NSInteger)b;
@end
@implementation Calc
- (NSInteger)execute:(NSInteger)a b:(NSInteger)b {
if (self.strategy == nil) {
return 0;
}
return [self.strategy doOperation:a b:b];
}
@end
//Client
Calc *calc = [[Calc alloc] init];
NSInteger result1 = [calc execute:5 b:3];
//result1 is 0
calc.strategy = [[AddStrategy alloc] init];
NSInteger result2 = [calc execute:5 b:3];
//result2 is 8
calc.strategy = [[SubstractStrategy alloc] init];
NSInteger result3 = [calc execute:5 b:3];
//result3 is 2
NSLog(@"result1 is %ld", (long)result1);
NSLog(@"result2 is %ld", (long)result2);
NSLog(@"result3 is %ld", (long)result3);
| Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. |