美文网首页
iOS 策略模式

iOS 策略模式

作者: 印林泉 | 来源:发表于2017-03-03 17:20 被阅读93次
  • 策略模式
    定义一系列的算法,将每一个算法封装起来,并且这些算法之间可以相互替换。
    抽象策略类,为所有支持或相关算法声明共同接口,用策略接口来实现相关算法的具体策略类。场景类对象使用策略接口多态调用具体策略类对应的方法。
    策略类是对象的一部分。

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

验证策略模式

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

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

@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:@"1546310515@qq.com"];
        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 <UIKit/UIKit.h>
#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 ()<UITextFieldDelegate>
///输入邮箱的验证
@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策略模式和多态

    策略模式是一种常见的软件设计模式,这里简单得介绍一下策略模式并用IOS简单实现一下。所谓的策略模式,顾名思义是要采...

  • 设计模式

    iOS设计模式(5)策略模式 iOS适配器设计模式其实就是对某个控件上的各个部分,用一个model来统一赋值,而在...

  • iOS - 策略模式

    定义 策略模式是一种比较简单的模式,也叫政策模式。定义一系列的算法,把它们一个个封装起来,并且使它们可相互替代。 ...

  • iOS 策略模式

    策略模式 原文链接 : 链接定义一系列的算法, 并且将每一个算法封装起来, 算法之间还可以相互替换可以看下图来...

  • iOS策略模式

    用处:让算法和对象分开来,使得算法可以独立于使用它的客户而变化。 例子:出行旅游,我们 可以有几个策略可以考虑,可...

  • iOS 策略模式

    策略模式定义一系列的算法,将每一个算法封装起来,并且这些算法之间可以相互替换。抽象策略类,为所有支持或相关算法声明...

  • 2020-04-16

    iOS设计模式-策略模式 面向对象的设计模式中,我们可以把相关的算法分离为不同的类,成为策略。与这种做法相关的一种...

  • 《iOS开发》--------常用的设计模式

    关于iOS开发中的设计模式,当下有集中最常用的设计模式:代理模式、观察者模式、MVC模式、单例模式、策略模式、工厂...

  • iOS设计模式-策略模式

    简介 策略模式就是根据不同的程序场景来使用不同的策略,一般用在有if 判断或switch case中,可以避免把不...

  • iOS设计模式-策略模式

    策略模式 将一系列的算法单独封装起来,使调用者在使用的时候,可以互相替换。 企鹅案例 这里我们需要几个企鹅,那这几...

网友评论

      本文标题:iOS 策略模式

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