美文网首页设计模式面试专题(重难点)
iOS 设计模式的应用 ⑰ 策略模式

iOS 设计模式的应用 ⑰ 策略模式

作者: _涼城 | 来源:发表于2022-05-20 07:07 被阅读0次

    前言

        开发中可能常常出现这样的情景:把一堆算法塞到同一段代码中,然后使用 if-else 或者 switch-case 条件语句来决定要使用哪个算法? 这些算法可能是一堆相似的类函数或方法,用以解决相关的问题。例如,有一个验证输入数据例程。数据本身可以是任何数据类型。每种数据类型需要不同的验证算法。如果能把每个算法封装成一个对象,那么就能消除根据数据类型决定使用什么算法的 if-else 语句。

        面向对象软件设计中,可以把相关算法分离为不同的类 ,成为策略。与这种做法有关的一种设计模式称为策略模式

    什么是策略模式

        策略模式定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。其中关键角色是策略类,为所有支持的或相关的算法声明了一个共同接口。另外还有使用策略接口来实现相关算法的具体策略类。场景(context)类的对象配置一个具体策略对象的实例,场景对象使用策略接口调用由具体策略类定义的算法。

    策略模式的类结构.png

        一组算法或者说算法的一个层次结构,以 ConcreteStrategy 类的形式,共享相同的 algorithmInterface 接口,这样 Context 就能使用相同的接口访问算法的各种变体。

    什么时候使用策略模式

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

    策略模式的优缺点

    策略模式的优点

    1. 算法可以自由切换。
    2. 避免使用多重条件判断。
    3. 扩展性良好。

    策略模式的缺点

    1. 策略类会增多。
    2. 所有策略类都需要对外暴露。

    策略模式的实现

        举个简单的例子,假设应用程序中需要有个 UITextField 以接受用户的输入,然后要在应用程序的处理中使用这个输入值。为了保证每个字段的输入有效,可以在失去焦点时 textFieldDidEndEditing: 中作些验证,比如某个字段只接受数值型,另一个字段只接受字母,但是如何区分这个文本框是什么类型的呢?

    如果不使用策略模式,代码会是下面这个样子:

    if(textFiled == numberTextField){
      //...
    }else if (textField == alphaTextField){
      //...
    }
    //...
    

        现在的目标是把这些验证检查提到各种策略中,这样它们就能在委托和其它方法之重用。每个验证都是从文本框取出输入值,然后根据所需的策略进行验证,最后返回一个 BOOL 值,如果验证失败,还会返回一个 NSError 实例。

        定义一个抽象基类 InputValidator, validateInput:error 方法,声明子类的公共行为将验证文本框的内容。

    static NSString * const InputValidationErrorDomain = @"InputValidationErrorDomain";
    
    @interface InputValidator : NSObject 
    {
    
    }
    // A stub for any actual validation strategy
    - (BOOL) validateInput:(UITextField *)input error:(NSError **) error;
    
    @end
    @implementation InputValidator
    
    // A stub for any actual validation strategy
    - (BOOL) validateInput:(UITextField *)input error:(NSError **) error
    {
      if (error)
      {
        *error = nil;
      }
      
      return NO;
    }
    
    @end
    

        实现数字验证器 NumericInputValidator

    @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
    @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

    @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
    @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
    
    

        创建自定义的 UITextField 关联 InputValidator,通过 validate 方法执行校验

    @interface CustomTextField : UITextField 
    {
      @private
      InputValidator *inputValidator_;
    }
    
    @property (nonatomic, strong) InputValidator *inputValidator;
    
    - (BOOL) validate;
    
    @end
    @implementation CustomTextField
    
    @synthesize inputValidator=inputValidator_;
    
    - (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];
        [alertView release];
      }
      
      return validationResult;
    }
    
    
    @end
    

    总结

        策略模式主要解决在有多种算法相似的情况下,使用if...else 所带来的复杂和难以维护。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的context 对象。策略对象改变 context 对象的执行算法。策略模式与装饰模式有些相似。装饰器从外部扩展对象的行为,而各种策略则被封装在对象之中,所以说装饰器改变对象的“外表”,而策略改变对象的“内容”。需要注意的是,如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。

    相关文章

      网友评论

        本文标题:iOS 设计模式的应用 ⑰ 策略模式

        本文链接:https://www.haomeiwen.com/subject/tvoxprtx.html