策略(Startegy)模式

本文介绍了策略模式的基本概念,通过示例展示了如何实现简单的策略模式。包括创建策略基类、具体策略类及上下文环境,最后演示了如何在客户端进行调用。

基本概念

策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,不会影响到使用算法的客户。



简单策略的实现:

(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)角色:包装了相关的算法或行为;

结论:

策略模式是一种定义一系列算法的方法,从概念上来看,所有的算法完成的都是相同的工作,他可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

策略模式的Strategy类层次为Context定义了一些列可供重用的算法或行为。继承有助于析取出这些算法中的公共功能
策略模式的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试
策略模式是用来封装算法的,但是实际中我们可以用他来封装几乎任何类型的规则,只要是在分析过程中需要不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性
基本的策略模式中,选择所有具体实现的职责由客户端对象承担,并转给策略模式的context对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值