基本概念
策略模式:定義了演算法家族,分別封裝起來,讓他們之間可以互相替換,不會影響到使用演算法的客戶。
簡單策略的實現:
(1)建立Strategy的基類,定義所有Strategy都要實現的相同的方法,定義所有支援的演算法的公共介面,例如播放器有播放,停止等
@interface StragegyBaseObject : NSObject
- (void)tryStragegyLog;
- (void)play;
- (void)stop;
@end
#import "StragegyBaseObject.h"
@implementation StragegyBaseObject
@end
(2)建立兩個類,分別繼承StragegyBaseObject,實現所有的公用方法
#import "StragegyFirst.h"
@implementation StragegyFirst
- (void)tryStragegyLog
{
NSLog(@"StragegyFirst");
}
- (void)play
{
NSLog(@"StragegyFirst play");
}
- (void)stop
{
NSLog(@"StragegyFirst stop");
}
@end
#import "StagegySecond.h"
@implementation StagegySecond
- (void)tryStragegyLog
{
NSLog(@"StagegySecond");
}
- (void)play
{
NSLog(@"StagegySecond play");
}
- (void)stop
{
NSLog(@"StagegySecond stop");
}
@end
(3)建立context
#import <Foundation/Foundation.h>
#import "StragegyBaseObject.h"
typedef enum : NSUInteger {
StrategyContextTypeFirst,
StrategyContextTypeSecond,
} StrategyContextType;
@interface StrategyContext : NSObject
@property (nonatomic, strong)StragegyBaseObject *stragegy;
- (instancetype)initWithStrategyContextType:(StrategyContextType)type;
- (void)tryStragegyLog;
- (void)play;
- (void)stop;
@end
#import "StrategyContext.h"
#import "StragegyFirst.h"
#import "StagegySecond.h"
@implementation StrategyContext
- (instancetype)initWithStrategyContextType:(StrategyContextType)type
{
self = [super init];
if (self) {
switch (type) {
case StrategyContextTypeFirst:
{
self.stragegy = [[StragegyFirst alloc] init];
}
break;
case StrategyContextTypeSecond:
{
self.stragegy = [[StagegySecond alloc] init];
}
break;
default:
break;
}
}
return self;
}
- (void)tryStragegyLog
{
[self.stragegy tryStragegyLog];
}
- (void)play
{
[self.stragegy play];
}
- (void)stop
{
[self.stragegy stop];
}
@end
(4)最終呼叫
StrategyContext *context = [[StrategyContext alloc] initWithStrategyContextType:StrategyContextTypeSecond];
[context tryStragegyLog];
[context play];
環境(Context)角色:持有一個Strategy的引用;
抽象策略(Strategy)角色:這是一個抽象角色,通常由一個介面或抽象類實現。此角色給出所有的具體策略類所需的介面;
具體策略(ConcreteStrategy)角色:包裝了相關的演算法或行為;