策略模式

2018-01-02  本文已影响9人  QG不吃鱼的猫

通俗的去描述策略:同样的结果,不一样的显示策略。

如果没有策略模式可能我们要用if-else写很多无奈的代码

UML图如下:

插播一个组合(Composition)和聚合(Aggregation)的区别:

组合(图 1) 聚合(图 2)

外貌:组合是实心的、聚合是空心的。

实质:组合的个体不是一个独立的业务单元、聚合的个体可以处理单独的业务单元。

Composition表示的是'Part-of'的关系, 以图1为例,Engine是Car的一部分。脱离Car的Engine是没有实在意义的;而     Aggregation表示的是'Has-a'的关系,以图2为例,Person有一个Address,但是Addess的存在是不依赖Person的,换句话说,地址本身就有其独立存在的意义,有没有人都是没有关系的。

OC代码去实现这个UML图:

策略接口类:

#import <UIKit/UIKit.h>

@protocol TextFieldValidate

- (BOOL)validateInputTextField:(UITextField *)textField;

@end

实现接口的策略子类:

#import <UIKit/UIKit.h>

#import "TextFieldValidate.h"

@interface LetterCheckValidate : NSObject<TextFieldValidate>

@end

#import "LetterCheckValidate.h"

@implementation LetterCheckValidate

-(BOOL)validateInputTextField:(id)textField {

UITextField * mtextField = (UITextField *)textField;

if (mtextField.text.length == 0) {

return NO;

}

// ^[a-zA-Z]*$ 从开头(^)到结尾($), 有效字符集([a-zA-Z])或者更多(*)个字符 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];

NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];

if(numberOfMatches == 0) {

NSLog(@"不全是字母");

}else {

NSLog(@"都是字母"); } return numberOfMatches == 0 ? NO : YES;

}

@end

策略接口被组合:

#import <UIKit/UIKit.h>

#import "TextFieldValidate.h"

@interface NumberCheckValidate : NSObject<TextFieldValidate>

@end

#import "NumberCheckValidate.h"

@implementation NumberCheckValidate

-(BOOL)validateInputTextField:(id)textField {

UITextField * mtextField = (UITextField *)textField;

if (mtextField.text.length == 0) { return NO; }

// ^[a-zA-Z]*$ 从开头(^)到结尾($), 有效字符集([a-zA-Z])或者更多(*)个字符 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];

NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];

if(numberOfMatches == 0) {

    NSLog(@"不全是数字");

}else {

    NSLog(@"都是数字");

}

return numberOfMatches == 0 ? NO:YES;

}

@end

代码调用展示:

@interface ViewController ()

@property (weak, nonatomic) IBOutlet CustomTextField *field1;

@property (weak, nonatomic) IBOutlet CustomTextField *field2;

@end

- (void)viewDidLoad {

[super viewDidLoad];

// 初始化

self.field1.inputValidate = [LetterCheckValidate new];

self.field2.inputValidate = [NumberCheckValidate new];

@weakify(self);

[self.field1.rac_textSignal subscribeNext:^(NSString * x) {

    @strongify(self);

    [self.field1 validate];

}];

[self.field2.rac_textSignal subscribeNext:^(NSString * x) {

    @strongify(self);

    [self.field2 validate];

}];

}

1、输入前 2、输入后 2、输出日志
上一篇下一篇

猜你喜欢

热点阅读