iOS 策略模式

  • 策略模式
    定义一系列的算法,将每一个算法封装起来,并且这些算法之间可以相互替换。
    抽象策略类,为所有支持或相关算法声明共同接口,用策略接口来实现相关算法的具体策略类。场景类对象使用策略接口多态调用具体策略类对应的方法。
    策略类是对象的一部分。

  • 应用,适用场景
    已知策略,用验证策略验证邮箱、电话号码格式。

验证策略模式

//
//  InputValidator.h
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import 
#import 

@interface InputValidator : NSObject

///策略的输入
- (BOOL)validateInput:(UITextField *)input;

@property (strong, nonatomic)NSString *errorMessage;

@end
//
//  InputValidator.m
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "InputValidator.h"

@implementation InputValidator

- (BOOL)validateInput:(UITextField *)input {
    return NO;
}

@end

邮箱验证策略模式

//
//  EmailValidator.h
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "InputValidator.h"

@interface EmailValidator : InputValidator

///重载了父类的验证方法
- (BOOL)validateInput:(UITextField *)input;

@end
//
//  EmailValidator.m
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "EmailValidator.h"

#ifndef DisableRegExCategoriesMacros
#define RX(pattern) [[NSRegularExpression alloc] initWithPattern:pattern]
#endif

@implementation EmailValidator

- (BOOL)validateInput:(UITextField *)input {
    if (input.text.length <= 0) {
        self.errorMessage = @"没有输入";
    } else {
        BOOL isMatch = [input.text isEqualToString:@"[email protected]"];
        if (isMatch == NO) {
            self.errorMessage = @"请输入正确的邮箱";
        } else {
            self.errorMessage = nil;
        }
    }
    return self.errorMessage == nil ? YES : NO;
}

@end

电话号码验证策略模式

//
//  PhoneNumberValidator.h
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "InputValidator.h"

@interface PhoneNumberValidator : InputValidator

///重载了父类的验证方法
- (BOOL)validateInput:(UITextField *)input;

@end
//
//  PhoneNumberValidator.m
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "PhoneNumberValidator.h"

@implementation PhoneNumberValidator

- (BOOL)validateInput:(UITextField *)input {
    if (input.text.length <= 0) {
        self.errorMessage = @"没有输入";
    } else {
        BOOL isMatch = [input.text isEqualToString:@"18721409352"];
        if (isMatch == NO) {
            self.errorMessage = @"请输入正确的手机号码";
        } else {
            self.errorMessage = nil;
        }
    }
    return self.errorMessage == nil ? YES : NO;
}

@end

自定义输入框

//
//  CustomTextField.h
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import 
#import "InputValidator.h"///输入验证器

@interface CustomTextField : UITextField

///抽象的策略
@property (strong, nonatomic) InputValidator *validator;

///初始化
- (instancetype)initWithFrame:(CGRect)frame;

///验证输入合法性
- (BOOL)validate;

@end
//
//  CustomTextField.m
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "CustomTextField.h"

@implementation CustomTextField

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, self.frame.size.height)];
    self.leftView = leftView;
    self.leftViewMode = UITextFieldViewModeAlways;
    self.font = [UIFont fontWithName:@"Avenir-Book" size:12.f];
    self.layer.borderWidth = 0.5f;
}

- (BOOL)validate {
    return [self.validator validateInput:self];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

使用

//
//  ViewController.m
//  LearnStrategy
//
//  Created by 印林泉 on 2017/3/3.
//  Copyright © 2017年 yiq. All rights reserved.
//

#import "ViewController.h"
#import "CustomTextField.h"
#import "EmailValidator.h"
#import "PhoneNumberValidator.h"

#define Width [UIScreen mainScreen].bounds.size.width

@interface ViewController ()
///输入邮箱的验证
@property (nonatomic, strong) CustomTextField  *emailTextField;
///输入电话号码的验证框
@property (nonatomic, strong) CustomTextField  *phoneNumberTextField;

/////验证email地址
//- (NSString *)validateEmailInput:(UITextField *)input;
/////验证电话号码
//- (NSString *)validatePhoneNumberInput:(UITextField *)input;
//
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    ///初始化按钮
    [self initButton];
    ///初始化验证框
    [self initCustomTextFields];
}

- (void)initCustomTextFields {
    self.emailTextField = [[CustomTextField alloc] initWithFrame:CGRectMake(30, 80, Width - 60, 30)];
    self.emailTextField.placeholder = @"请输入邮箱";
    self.emailTextField.delegate = self;
    self.emailTextField.validator = [EmailValidator new];
    [self.view addSubview:self.emailTextField];
    
    
    self.phoneNumberTextField = [[CustomTextField alloc] initWithFrame:CGRectMake(30, 80 + 40, Width - 60, 30)];
    self.phoneNumberTextField.placeholder = @"请输入电话号码";
    self.phoneNumberTextField.delegate = self;
    self.phoneNumberTextField.validator = [PhoneNumberValidator new];
    [self.view addSubview:self.phoneNumberTextField];
}

#pragma mark - 初始化按钮以及按钮事件
- (void)initButton {
    UIButton *button = [[UIButton alloc] initWithFrame:(CGRect){0, 30, 90, 30}];
    [button setTitle:@"back" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonsEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonsEvent:(UIButton *)button {
    [self.view endEditing:YES];
}

#pragma mark - 文本框代理
- (void)textFieldDidEndEditing:(UITextField *)textField {
    CustomTextField *customTextField = (CustomTextField *)textField;
    if ([customTextField validate] == NO) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:customTextField.validator.errorMessage preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

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

@end

抽象父类方法延迟到子类实现。

你可能感兴趣的:(iOS 策略模式)