策略模式

/*

策略(Strategy)模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。看到策略模式的时候有的时候跟简单工厂相比较,其实有很大的迷惑性,都是继承多态感觉没有太大的差异性,简单工厂模式是对对象的管理,策略模式是对行为的封装。

*/

#import

//  Strategy抽象类

@interface SoftWarStragegy : NSObject

- (void)installStrategy;

@end

#import "SoftWarStragegy.h"

@implementation SoftWarStragegy

- (void)installStrategy

{

}

@end

#import "SoftWarStragegy.h"

@interface XcodeStrategy : SoftWarStragegy

@end

#import "XcodeStrategy.h"

@implementation XcodeStrategy

- (void)installStrategy

{

NSLog(@"Xcode安装成功");

}

@end

#import "SoftWarStragegy.h"

@interface QQStragegy : SoftWarStragegy

@end

#import "QQStragegy.h"

@implementation QQStragegy

- (void)installStrategy

{

NSLog(@"QQ安装成功");

}

@end

#import#import "SoftWarStragegy.h"

//在此策略下按功能需求实例化对象

typedef NS_OPTIONS(NSInteger, StrategyType){

StrategyXcode = 1,

StrategyQQ = 1 << 1,

StrategyAll = StrategyQQ | StrategyXcode

} ;

//如何实现策略并发

@interface SoftWareContext : NSObject

- (instancetype)initWithStrategyType:(StrategyType)type;

- (void)installResult;

@end

#import "SoftWareContext.h"

#import "XcodeStrategy.h"

#import "QQStragegy.h"

@interface SoftWareContext ()

@property (strong , nonatomic) SoftWarStragegy *sortwar;

@end

@implementation SoftWareContext

- (instancetype)initWithStrategyType:(StrategyType)type

{

if (self = [super init]) {

switch (type) {

case StrategyXcode:

self.sortwar = [[XcodeStrategy alloc] init];

break;

case StrategyQQ:

self.sortwar = [[QQStragegy alloc] init];

break;

case StrategyXcode | StrategyQQ:

break;

}

}

return self;

}

- (void)installResult

{

[self.sortwar installStrategy];

}

@end


#import#import "SoftWareContext.h"

int main(int argc, const char * argv[]) {

@autoreleasepool {

SoftWareContext *one = [[SoftWareContext alloc] initWithStrategyType:StrategyXcode];

[one installResult];

SoftWareContext *two = [[SoftWareContext alloc] initWithStrategyType:StrategyQQ];

[two installResult];

}

return 0;

}

你可能感兴趣的:(策略模式)