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

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

    NSError *regError = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];
     
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:input.text options:NSMatchingAnchored range:NSMakeRange(0, input.text.length)];
    // 如果没有匹配,就会错误和NO.
    if (numberOfMatches == 0) {
        if (error != nil) {
            // 先判断error对象是存在的
            NSString *description = NSLocalizedString(@"验证失败", @"");
            NSString *reason = NSLocalizedString(@"输入仅能包字母", @"");
            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]; //错误被关联到定制的错误代码1002和在InputValidator的头文件中。
        }
         
        return NO;
    }
     
    return YES;
}
 
@end
    AlphaInputValidator也是实现了validateInput方法的InputValidator类型。它的代码结构和算法跟NumberInputValidator相似,只是使用了不同的正则表达式,不同错误代码和消息。可以看到两个版本的代码有很多重复。两个算法结构相同,我们可以把这个结构,我们可以把这个结构重构成抽象父类的模板方法(将在下一篇博客中,来进行实现)。

 

    至此,我们已经写好了输入验证器,可以在客户端来使用了,但是UITextField不认识它们,所以我们需要自己的UITextField版本。我们要创建UITextField的子类,其中有一个InputValidator的引用,以及一个方法validate。代码如下: