架构学习研究--策略模式

概念

定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。也称为政策模式

目的

算法和对象分开来,使得算法可以独立于使用它的客户而变化

我们经常可以看到一些不成熟的代码,在viewcontroller中,写了好多ifelse,使得controller很冗长,并且不方便阅读。为了解耦

结构

这里写图片描述
  1. 定义一个抽象类,定义几个抽象方法
  2. 创建实体类,实现抽象类的抽象方法
  3. 创建实体类,调用这个抽象类。这个实体类和抽象类是聚合关系

实例

没有使用策略模式

@interface ViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *letterInput; /**< 字母输入 */
@property (weak, nonatomic) IBOutlet UITextField *numberInput; /**< 数字输入 */
@property (nonatomic, strong) UIButton *btnPrint;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.letterInput.delegate = self;
    self.numberInput.delegate = self;
}

- (IBAction)btnClick:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate实现
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.letterInput) {
        // 验证输入值,确保它输入的是字母
        NSString *outputLatter = [self validateLatterInput:textField];
       
        NSLog(@"-----%@",outputLatter);
            
     
        
    } else if (textField == self.numberInput){
        // 验证输入值,确保它输入的是数字
        NSString *outputNumber = [self validateNumberInput:textField];
        
        NSLog(@"-----%@",outputNumber);
            
      
    }
}

#pragma mark - 验证输入
- (NSString *)validateLatterInput:(UITextField *)textField {
    // 1.判断没有输入就返回
    if(textField.text.length == 0) {
        return @"--输入是空的---";
    }
    
    // 2.用正则验证
    // 从开头(表示^)到结尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azcccc
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" 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;
}

- (NSString *)validateNumberInput:(UITextField *)textField {
    // 1.判断没有输入就返回
    if(textField.text.length == 0) {
        return @"--输入是空的---";
    }
    
    // 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;
}

实现效果就是有两个输入框,验证一个只能输入字母,一个只能输入数字


这里写图片描述

使用策略模式

按照架构图,我们需要创建一个抽象类InputTextFieldValidate,两个实现类LatterTextFieldValidate和NumberTextFieldValidate,以及调用抽象类的实体类CustomTextField。

这里写图片描述

1.在抽象类,编写抽象方法

@interface InputTextFieldValidate : NSObject

// 策略输入 返回验证的结果
- (NSString*)validateInputTextField:(UITextField *)textField;

// 输出的属性字符串
@property (nonatomic, strong) NSString *attributeInputStr;
@implementation InputTextFieldValidate
// 抽象类不实现
- (NSString*)validateInputTextField:(UITextField *)textField {
    return nil;
}

@end

2.让两个实现类实现这两个抽象方法

@implementation LatterTextFieldValidate

- (NSString*)validateInputTextField:(UITextField *)textField {
    
    // 1.判断没有输入就返回
    if(textField.text.length == 0) {
        self.attributeInputStr = @"字母不能是空的";
        return self.attributeInputStr;
    }
    
    // 2.用正则验证
    // 从开头(表示^)到结尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azcccc
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" 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) {
        self.attributeInputStr = @"不全是字母,输入有问题,请重新输入";
    } else {
        self.attributeInputStr = @"输入正确,全是字母";
    }
    return self.attributeInputStr ;
}


- (NSString*)validateInputTextField:(UITextField *)textField {
    // 1.判断没有输入就返回
    if(textField.text.length == 0) {
        self.attributeInputStr = @"数值不能是空的";
        return self.attributeInputStr;
    }
    
    // 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) {
        self.attributeInputStr = @"不全是数字,输入有问题,请重新输入";
    } else {
        self.attributeInputStr = @"输入正确,全是数字";
    }
    return self.attributeInputStr ;
}

3.聚合类调用抽象方法

@interface CustomTextField : UITextField

// 抽象的策略
@property (nonatomic, strong) InputTextFieldValidate *inputValidate;

// 验证
- (void)validate;

@end

@implementation CustomTextField

- (void)validate {
 
        NSLog(@"----%@", [self.inputValidate validateInputTextField:self]);
   
    
//    return result;
}
@end

4.controller调用


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.letterInput.delegate = self;
    self.numberInput.delegate = self;
    
    // 初始化
    self.letterInput.inputValidate = [LatterTextFieldValidate new];
    self.numberInput.inputValidate = [NumberTextFieldValidate new];
    
}

- (IBAction)btnClick:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate实现
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([textField isKindOfClass:[CustomTextField class]]) {
        
        [(CustomTextField *)textField validate];
    }
}

最终效果还是一样的,但是controller的代码量减少了,可读性、复用性大大提高。
但是缺点显而易见,多了很多类

注意

  1. 使用这个模式,必须是知道固有场景,比如这个实例是知道两个输入框一个严重字母,一个验证数字
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,576评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,515评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,017评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,626评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,625评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,255评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,825评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,729评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,271评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,363评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,498评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,183评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,867评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,338评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,458评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,906评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,507评论 2 359

推荐阅读更多精彩内容