策略模式

Objective-C编程之道 iOS设计模式解析
iOS设计模式解析-工厂模式
iOS设计模式解析-抽象工厂模式
iOS设计模式解析-外观模式
iOS设计模式解析-中介者模式
iOS设计模式解析-观察者模式
iOS设计模式解析-装饰模式
iOS设计模式解析-责任链模式
iOS设计模式解析-模板方法
iOS设计模式解析-策略模式
iOS设计模式解析-享元模式
iOS设计模式解析-代码地址

何为策略模式

策略模式中的一个关键角色是策略类,它为所有支持的或相关的算法声明了一个共同接口。另外,还有使用策略接口来实现相关算法的具体策略类,场景类的对象配置有一个具体策略对象的实例,场景对象使用策略接口调用由具体策略类定义的算法。

何时使用策略模式

在以下情形,自然会考虑使用这一模式。

  • 一个类在其操作中使用多个条件语句来定义许多行为,我们可以把相关的条件分支移到它们自己的策略类中。
  • 需要算法的各种变体。
  • 需要避免把复杂的,与算法相关的数据结构暴露给客户端。

在UITextField中应用验证策略

创建InputValidator类

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

static NSString * const InputValidationErrorDomain = @"InputValidationErrorDomain";

@interface InputValidator : NSObject 

// A stub for any actual validation strategy
- (BOOL) validateInput:(UITextField *)input error:(NSError **) error;

@end
#import "InputValidator.h"


@implementation InputValidator

// A stub for any actual validation strategy
- (BOOL) validateInput:(UITextField *)input error:(NSError **) error
{
  if (error)
  {
    *error = nil;
  }
  
  return NO;
}

@end

创建CustomTextField类继承UITextField

#import <Foundation/Foundation.h>
#import "InputValidator.h"

@interface CustomTextField : UITextField 

@property (nonatomic, strong)  InputValidator *inputValidator;

- (BOOL) validate;

@end
#import "CustomTextField.h"

@implementation CustomTextField

- (BOOL) validate
{
  NSError *error = nil;
  BOOL validationResult = [_inputValidator validateInput:self error:&error];
  if (!validationResult)
  {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                                        message:[error localizedFailureReason]
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                              otherButtonTitles:nil];
    [alertView show];
  }
  return validationResult;
}
@end

创建NumericInputValidator继承InputValidator(只能输入数字算法)

#import <Foundation/Foundation.h>
#import "InputValidator.h"

@interface NumericInputValidator : InputValidator
// A validation method that makes sure the input only contains
// numbers i.e. 0-9
- (BOOL) validateInput:(UITextField *)input error:(NSError **) error;

@end
#import "NumericInputValidator.h"

@implementation NumericInputValidator

- (BOOL) validateInput:(UITextField *)input error:(NSError**) error
{
  NSError *regError = nil;
  NSRegularExpression *regex = [NSRegularExpression 
                                 regularExpressionWithPattern:@"^[0-9]*$"
                                 options:NSRegularExpressionAnchorsMatchLines 
                                 error:&regError];
  
  NSUInteger numberOfMatches = [regex 
                                numberOfMatchesInString:[input text]
                                options:NSMatchingAnchored
                                range:NSMakeRange(0, [[input text] length])];
  
  // if there is not a single match
  // then return an error and NO
  if (numberOfMatches == 0)
  {
    if (error != nil)
    {
      NSString *description = NSLocalizedString(@"Input Validation Failed", @"");
      NSString *reason = NSLocalizedString(@"The input can only contain numerical values", @"");
      
      NSArray *objArray = [NSArray arrayWithObjects:description, reason, nil];
      NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,
                           NSLocalizedFailureReasonErrorKey, nil];
      
      NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray
                                                           forKeys:keyArray];
      *error = [NSError errorWithDomain:InputValidationErrorDomain
                                   code:1001
                               userInfo:userInfo];
    }
    return NO;
  }
  
  return YES;
}
@end

创建AlphaInputValidator继承InputValidator(只能输入字母算法)

#import <Foundation/Foundation.h>
#import "InputValidator.h"

@interface AlphaInputValidator : InputValidator
// A validation method that makes sure the input only 
// contains letters only i.e. a-z A-Z
- (BOOL) validateInput:(UITextField *)input error:(NSError **) error;

@end
#import "AlphaInputValidator.h"

@implementation AlphaInputValidator

- (BOOL) validateInput:(UITextField *)input error:(NSError **) error
{
  NSRegularExpression *regex = [NSRegularExpression 
                                 regularExpressionWithPattern:@"^[a-zA-Z]*$"
                                 options:NSRegularExpressionAnchorsMatchLines 
                                 error:nil];
  
  NSUInteger numberOfMatches = [regex 
                                numberOfMatchesInString:[input text]
                                options:NSMatchingAnchored
                                range:NSMakeRange(0, [[input text] length])];
  
  // If there is not a single match
  // then return an error and NO
  if (numberOfMatches == 0)
  {
    if (error != nil) 
    {
      NSString *description = NSLocalizedString(@"Input Validation Failed", @"");
      NSString *reason = NSLocalizedString(@"The input can only contain letters", @"");
      
      NSArray *objArray = [NSArray arrayWithObjects:description, reason, nil];
      NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,
                           NSLocalizedFailureReasonErrorKey, nil];
      
      NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray
                                                           forKeys:keyArray];
      *error = [NSError errorWithDomain:InputValidationErrorDomain
                                   code:1002
                               userInfo:userInfo];
    }
    return NO;
  }
  return YES;
}
@end

主类调用

#import "ViewController.h"
#import "CustomTextField.h"
#import "AlphaInputValidator.h"
#import "NumericInputValidator.h"

@interface ViewController ()<UITextFieldDelegate>

@property (nonatomic, strong)  CustomTextField *numericTextField;
@property (nonatomic, strong)  CustomTextField *alphaTextField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    _numericTextField = [[CustomTextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
    _numericTextField.backgroundColor = [UIColor blueColor];
    _numericTextField.delegate = self;
    _numericTextField.inputValidator = [[NumericInputValidator alloc]init];
    _numericTextField.placeholder = @"_numericTextField";
    _numericTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _numericTextField.font = [UIFont systemFontOfSize:16.f];
    _numericTextField.textColor = [UIColor whiteColor];
    
    [self.view addSubview:_numericTextField];
    _alphaTextField = [[CustomTextField alloc] initWithFrame:CGRectMake(100, 200, 100, 30)];
    _alphaTextField.inputValidator = [[AlphaInputValidator alloc]init];
    _alphaTextField.backgroundColor = [UIColor blueColor];
    _alphaTextField.placeholder = @"_alphaTextField";
    _alphaTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _alphaTextField.font = [UIFont systemFontOfSize:16.f];
    _alphaTextField.delegate = self;
    _alphaTextField.textColor = [UIColor whiteColor];
    [self.view addSubview:_alphaTextField];
}

#pragma mark -
#pragma mark UITextFieldDelegate methods

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField isKindOfClass:[CustomTextField class]])
    {
        [(CustomTextField*)textField validate];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

注意(这俩句代码很重要)
_numericTextField.inputValidator = [[NumericInputValidator alloc]init];
_alphaTextField.inputValidator = [[AlphaInputValidator alloc]init];

策略模式的优缺点

优点:
  • 提供了管理相关的算法族的办法。可以封装一些算法,不想让算法直接暴露出来。
  • 可以避免使用多重条件转移语句,消除根据类型决定使用什么算法的一些if-else的语句。
缺点:
  • 使用之前必须知道所有的策略,使用中不能动态改变,在实例话的时候就设定好需要使用的策略类了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容