iOS设计模式(一)策略模式

策略模式
  • 概念:定义一系列的算法,并且将每一个算法封装起来,算法间可以互相替换.(策略模式基于固定的输出).
策略模式UML
F3BE4105-4849-4ABD-B7D5-B9758A9B9585.png

聚合关系 Context把Stategy类引用过来,引用过来目的为了方便调stategy类的的方法(Context类引用stategy类的话,简单的说就时拥有了Stategy的属性).
stategy是抽象类,(抽象类指的是只有声明,没有实现,所有的继承都是由继承的子类contreteStrategyA,contreteStrategyB,contreteStrategyC来实现).


项目(非策略模式&策略模式对比)
  • 非策略模式(写在一个controller里面实现)
@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic, strong)UITextField *letterInput;
@property(nonatomic, strong)UITextField *numberInput;
@property(nonatomic, strong)UIButton *printBtn;
@implementation ViewController
- (void)viewDidLoad
{
   [super viewDidLoad];
   self.letterInput = [[UITextField alloc] initWithFrame:CGRectMake(10,100,self.view.frame.size.width - 2*10   , 40)];
   self.letterInput.placeholder = @"只接受字母";
   self.letterInput.delegate = self;
   self.letterInput.layer.borderWidth = 1;
   [self.view addSubview: self.letterInput];
   
   self.numberInput =  [[UITextField alloc] initWithFrame:CGRectMake(10,170,self.view.frame.size.width - 2*10   , 40)];
   self.numberInput.placeholder = @"只接受数字";
   self.numberInput.layer.borderWidth = 1;
   self.numberInput.delegate = self;
   [self.view addSubview: self.numberInput];

   self.printBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 240, self.view.frame.size.width - 2*10, 40)];
   self.printBtn.backgroundColor = [UIColor redColor];
   [self.printBtn setTitle:@"测试" forState:UIControlStateNormal];
   [self.printBtn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:self.printBtn];
}
- (void)action:(UIButton *)sender
{
   [self.view endEditing:YES];  
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
   if (textField == self.letterInput) {
               // 验证输入值,确保它输入的是字母
               NSString *outputLatter = [self validateLetterInput:textField];
               if (outputLatter) {
                   NSLog(@"-----%@",outputLatter);
       
               } else {
                   NSLog(@"--输入是空的---");
       
               }
   }
   else if (textField == self.numberInput){
               // 验证输入值,确保它输入的是数字
               NSString *outputNumber = [self validateNumberInput:textField];
               if (outputNumber) {
                   NSLog(@"-----%@",outputNumber);
       
               } else {
                   NSLog(@"--输入是空的---");
       
               }
   }
}

- (NSString *)validateLetterInput:(UITextField *)texField
{
   if (texField.text.length == 0) {
       return  nil;
   }
   
   //用正则表达式 从开头(表示^)到结尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azaaaa
   NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
   // NSMatchingAnchored 从开始处进行极限匹配r
   NSUInteger  numberOfMatches = [regex numberOfMatchesInString:[texField text] options:NSMatchingAnchored range:NSMakeRange(0, [texField.text length])];
   
       NSString *outLatter = nil;
       // 3.判断 匹配不符合表示0的话, 就走里面的漏记
       if (numberOfMatches == 0) {
           outLatter = @"不全是字母,输入有问题,请重新输入";
       } else {
           outLatter = @"输入正取,全是字母";
       }
       return outLatter;
}

- (NSString *)validateNumberInput:(UITextField *)textField
{
       // 1.判断没有输入就返回
       if(textField.text.length == 0) {
           return nil;
       }
   
       // 2.用正则验证
       // 从开头(表示^)到结尾(表示$)有效数字集(a-zA-Z)或者是更多(*)的字符  azcccc
       NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
       // NSMatchingAnchored 从开始处进行极限匹配
       NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];
       NSString *outLatter = nil;
       // 3.判断 匹配不符合表示0的话, 就走里面的漏记
       if (numberOfMatches == 0) {
           outLatter = @"不全是数字,输入有问题,请重新输入";
       } else {
           outLatter = @"输入正取,全是数字";
       }
       return outLatter;
}
@end
  • 策略模式

1.声明抽象类InputTextFieldValidate

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

@interface InputTextFieldValidate : NSObject
- (BOOL)validateInputTextField:(UITextField *)textfeild;
@property (nonatomic, strong)NSString *attributeInputStr;
@end

#import "InputTextFieldValidate.h"
#import <UIKit/UIKit.h>
@implementation InputTextFieldValidate
- (BOOL)validateInputTextField:(UITextField *)textfeild
{
    return NO;
}
@end

2.定义context类与InputTextFieldValidate类成聚合关系

#import <UIKit/UIKit.h>
#import "InputTextFieldValidate.h"

@interface CustomTextField : UITextField

@property(nonatomic, strong)InputTextFieldValidate *inputValidate;
//验证方法
- (BOOL)validate;
@end

#import "CustomTextField.h"

@implementation CustomTextField

- (BOOL)validate
{
    BOOL result = [self.inputValidate validateInputTextField:self];
    return result;
}
@end

3.继承InputTextFieldValidate的子类:LatterTextFieldValidate

#import "InputTextFieldValidate.h"
@interface LatterTextFieldValidate : InputTextFieldValidate
@end
#import "LatterTextFieldValidate.h"

@implementation LatterTextFieldValidate

- (BOOL)validateInputTextField:(UITextField *)textField
{
    if (textField.text.length == 0) {
        self.attributeInputStr = @"请输入字符";
        return  self.attributeInputStr;
    }
    
    //用正则表达式 从开头(表示^)到结尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azaaaa
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
    // NSMatchingAnchored 从开始处进行极限匹配r
    NSUInteger  numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [textField.text length])];
    
    
    // 3.判断 匹配不符合表示0的话, 就走里面的漏记
    if (numberOfMatches == 0) {
        self.attributeInputStr = @"不全是字母,输入有问题,请重新输入";
    } else {
        self.attributeInputStr = @"输入正取,全是字母";
    }
    
    return self.attributeInputStr==nil?YES:NO;

}

4.继承NumberTextFieldValidate的子类:NumberTextFieldValidate

#import "InputTextFieldValidate.h"

@interface NumberTextFieldValidate : InputTextFieldValidate

@end
#import "NumberTextFieldValidate.h"

@implementation NumberTextFieldValidate

- (BOOL)validateInputTextField:(UITextField *)textField
{
    // 1.判断没有输入就返回
    if(textField.text.length == 0) {
        self.attributeInputStr = @"请输入数字";
        return nil;
    }
    
    // 2.用正则验证
    // 从开头(表示^)到结尾(表示$)有效数字集(a-zA-Z)或者是更多(*)的字符  azcccc
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
    
    // NSMatchingAnchored 从开始处进行极限匹配
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];

    // 3.判断 匹配不符合表示0的话, 就走里面的漏记
    if (numberOfMatches == 0) {
         self.attributeInputStr = @"不全是数字,输入有问题,请重新输入";
    } else {
         self.attributeInputStr = @"输入正取,全是数字";
    }
    return  self.attributeInputStr==nil?YES:NO;
    
}
@end

5.策略模式抽象后的viewController

#import "ViewController.h"
#import "CustomTextField.h"
#import "LatterTextFieldValidate.h"
#import "NumberTextFieldValidate.h"

@interface ViewController ()<UITextFieldDelegate>

@property(nonatomic, strong)CustomTextField *letterInput;
@property(nonatomic, strong)CustomTextField *numberInput;
@property(nonatomic, strong)UIButton *printBtn;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.letterInput = [[CustomTextField alloc] initWithFrame:CGRectMake(10,100,self.view.frame.size.width - 2*10   , 40)];
    self.letterInput.placeholder = @"只接受字母";
    self.letterInput.delegate = self;
    self.letterInput.layer.borderWidth = 1;
    [self.view addSubview: self.letterInput];

    self.numberInput =  [[CustomTextField alloc] initWithFrame:CGRectMake(10,170,self.view.frame.size.width - 2*10   , 40)];
    self.numberInput.placeholder = @"只接受数字";
    self.numberInput.layer.borderWidth = 1;
    self.numberInput.delegate = self;
    [self.view addSubview: self.numberInput];
    
    self.printBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 240, self.view.frame.size.width - 2*10, 40)];
    self.printBtn.backgroundColor = [UIColor redColor];
    [self.printBtn setTitle:@"测试" forState:UIControlStateNormal];
    [self.printBtn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.printBtn];
    
    self.letterInput.inputValidate = [LatterTextFieldValidate new];
    self.numberInput.inputValidate = [NumberTextFieldValidate new];
}

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

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    if ([textField isKindOfClass:[CustomTextField class]]) {
        
        [(CustomTextField *)textField validate];
    }
}

@end
  • 优点:可以精简if-else的代码,解藕性高,可复用性高.
  • 缺点:知道固有的输入,在固定的场景下使用,代码量大,分类多.
    demo地址:https://github.com/defuliu/StrategyPatterns
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,283评论 6 530
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 97,947评论 3 413
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,094评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,485评论 1 308
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,268评论 6 405
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,817评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,906评论 3 440
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,039评论 0 285
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,551评论 1 331
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,502评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,662评论 1 366
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,188评论 5 356
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,907评论 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,304评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,563评论 1 281
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,255评论 3 389
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,637评论 2 370

推荐阅读更多精彩内容

  • 参考资料:菜鸟教程之设计模式 设计模式概述 设计模式(Design pattern)代表了最佳的实践,通常被有经验...
    Steven1997阅读 1,189评论 1 12
  • 设计模式基本原则 开放-封闭原则(OCP),是说软件实体(类、模块、函数等等)应该可以拓展,但是不可修改。开-闭原...
    西山薄凉阅读 3,831评论 3 14
  • 设计模式汇总 一、基础知识 1. 设计模式概述 定义:设计模式(Design Pattern)是一套被反复使用、多...
    MinoyJet阅读 3,955评论 1 15
  • 真诚的,TNANKS。 个人Github-23种设计模式案例链接 创建型模式 工厂模式 工厂模式(Factory ...
    水清_木秀阅读 26,111评论 11 204
  • 凌晨四点到中午11点,下午三点到晚七点,这是爸爸夏季在地里劳作的时间表,可以说除了吃饭睡觉都在地里。 旁边那家的婶...
    刘秀玲阅读 2,294评论 156 110