策略(Startegy)模式

基本概念

策略模式:定義了算法家族,分別封裝起來,讓他們之間可以互相替換,不會影響到使用算法的客戶。


簡單策略的實現(xiàn):

(1)創(chuàng)建Strategy的基類,定義所有Strategy都要實現(xiàn)的相同的方法,定義所有支持的算法的公共接口,例如播放器有播放,停止等

@interface StragegyBaseObject : NSObject

- (void)tryStragegyLog;

- (void)play;

- (void)stop;

@end

#import "StragegyBaseObject.h"

@implementation StragegyBaseObject

@end

(2)創(chuàng)建兩個類,分別繼承StragegyBaseObject,實現(xiàn)所有的公用方法

#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)創(chuàng)建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)最終調(diào)用

StrategyContext *context = [[StrategyContext alloc] initWithStrategyContextType:StrategyContextTypeSecond];

[context tryStragegyLog];

[context play];

環(huán)境(Context)角色:持有一個Strategy的引用;

抽象策略(Strategy)角色:這是一個抽象角色,通常由一個接口或抽象類實現(xiàn)。此角色給出所有的具體策略類所需的接口;

具體策略(ConcreteStrategy)角色:包裝了相關(guān)的算法或行為;

結(jié)論:

策略模式是一種定義一系列算法的方法,從概念上來看,所有的算法完成的都是相同的工作,他可以以相同的方式調(diào)用所有的算法,減少了各種算法類與使用算法類之間的耦合。

策略模式的Strategy類層次為Context定義了一些列可供重用的算法或行為。繼承有助于析取出這些算法中的公共功能

策略模式的優(yōu)點是簡化了單元測試,因為每個算法都有自己的類,可以通過自己的接口單獨測試

策略模式是用來封裝算法的,但是實際中我們可以用他來封裝幾乎任何類型的規(guī)則,只要是在分析過程中需要不同時間應用不同的業(yè)務規(guī)則,就可以考慮使用策略模式處理這種變化的可能性

基本的策略模式中,選擇所有具體實現(xiàn)的職責由客戶端對象承擔,并轉(zhuǎn)給策略模式的context對象

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容