iOS应用运用设计模式中的Strategy策略模式的开发实例

2020-01-14 22:14:28刘景俊

    我们设计一个抽象基类InputValidator,里面有一个validateInput:input error:error方法。分别有两个子类NumberInputValidator、AlphaInputValidator。具体的代码如下所示:

    InputValidator.h中抽象InputValidator的类声明

复制代码
static NSString *const InputValidationErrorDomain = @"InputValidationErrorDomain";
 
@interface InputValidator : NSObject
/**
 *  实际验证策略的存根方法
 */
- (BOOL)validateInput:(UITextField *)input error:(NSError *__autoreleasing *)error;
 
@end
    这个方法还有一个NSError指针的引用,当有错误发生时(即验证失败),方法会构造一个NSError实例,并赋值给这个指针,这样使用验证的地方就能做详细的错误处理。

 

    InputValidator.m中抽象InputValidator的默认实现

#import "InputValidator.h"
 

复制代码
@implementation InputValidator
 
- (BOOL)validateInput:(UITextField *)input error:(NSError *__autoreleasing *)error {
    if (error) {
        *error = nil;
    }
    return NO;
}
 
@end
    我们已经定义了输入验证器的行为,然后我们要编写真正的输入验证器了,先来写数值型的,如下:

 

    NumberInputValidator.h中NumberInputValidator的类定义

复制代码
#import "InputValidator.h"
 
@interface NumberInputValidator : InputValidator
 
/**
 *  这里重新声明了这个方法,以强调这个子类实现或重载了什么,这不是必须的,但是是个好习惯。
 */
- (BOOL)validateInput:(UITextField *)input error:(NSError *__autoreleasing *)error;
@end
    NumberInputValidator.m中NumberInputValidator的实现
复制代码
#import "NumberInputValidator.h"
 
@implementation NumberInputValidator
 
- (BOOL)validateInput:(UITextField *)input error:(NSError *__autoreleasing *)error {
    NSError *regError = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];