国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

iOS設(shè)計(jì)模式之策略模式

2019-11-14 18:34:19
字體:
供稿:網(wǎng)友

策略模式(Strategy)

基本理解

  • 面向?qū)ο蟮木幊蹋⒉皇穷愒蕉嘣胶茫惖膭澐质菫榱朔庋b,但分類的基礎(chǔ)是抽象,具有相同屬性和功能的對象的抽象集合才是類。
  • 策略模式:它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶。
  • 簡單工廠模式需要讓客戶端認(rèn)識兩個(gè)類,而策略模式和簡單工廠結(jié)合的用法,客戶端只需要認(rèn)識一個(gè)類就可以了。耦合更加降低。
  • 當(dāng)不同的行為堆砌在一個(gè)類中時(shí),就很難避免使用條件語句來選擇合適的行為。將這些行為封裝在一個(gè)個(gè)獨(dú)立的Strategy類中,可以再使用這些行為的類中消除條件語句。
  • 策略模式就是用來封裝算法的,但在實(shí)踐中,我們發(fā)現(xiàn)用它來封裝幾乎任何類型的規(guī)則,只要在分析過程中聽到了需要在不同時(shí)間應(yīng)用不同的業(yè)務(wù)規(guī)則,就可以考慮使用策略模式處理這種變化的可能性。
  • 在基本的策略模式中,選擇所用具體實(shí)現(xiàn)的職責(zé)由客戶端對象承擔(dān),并轉(zhuǎn)給策略模式的Context對象。
  • 面向?qū)ο筌浖O(shè)計(jì)中,我們可以把相關(guān)算法分離為不同的類,成為策略。
  • 策略模式中的一個(gè)關(guān)鍵角色是策略類,它為所有支持的或者相關(guān)的算法聲明了一個(gè)共同接口。
  • 控制器和試圖之間是一種基于策略模式的關(guān)系。

優(yōu)點(diǎn)

  • 策略模式是一種定義一系列算法的方法,從概念上來看,所有這些算法完成的都是相同的工作,只是實(shí)現(xiàn)不同,它可以以相同的方式調(diào)用所有的算法,減少了各種算法類與使用算法類之間的耦合。
  • 策略模式的Stategy類層次為Context定義了一些列的可供重用的算法或行為。繼承有助于析取出算法中的公共功能。
  • 策略模式的優(yōu)點(diǎn)是簡化了單元測試,因?yàn)槊總€(gè)算法都有自己的類,可以通過自己的接口單獨(dú)測試。

使用場景

  • 一個(gè)類在其操作中使用多個(gè)條件語句來定義許多行為。我們可以把相關(guān)的條件分支移到他們自己的策略類中
  • 需要算法的各種變體
  • 需要避免把復(fù)雜的、與算法相關(guān)的數(shù)據(jù)結(jié)構(gòu)暴露給客戶端

例子

該例子主要利用策略模式來判斷UITextField是否滿足輸入要求,比如輸入的只能是數(shù)字,如果只是數(shù)字就沒有提示,如果有其他字符則提示出錯(cuò)。驗(yàn)證字母也是一樣。
首先,我們先定義一個(gè)抽象的策略類iputValidator。代碼如下:
InputValidator.h

  	////  InputValidator.h//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>static NSString * const InputValidationErrorDomain = @"InputValidationErrorDomain";@interface InputValidator : NSObject//實(shí)際驗(yàn)證策略的存根方法-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end

InputValidator.m

////  InputValidator.m//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@implementation InputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{    if (error) {        *error = nil;    }    return NO;}@end

這個(gè)就是一個(gè)策略基類,然后我們?nèi)?chuàng)建兩個(gè)子類NumericInputValidator和AlphaInputValidator。具體代碼如下:
NumericIputValidator.h

////  NumericInputValidator.h//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@interface NumericInputValidator : InputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end

NumericIputValidator.m

////  NumericInputValidator.m//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "NumericInputValidator.h"@implementation NumericInputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{    NSError *regError = nil;    //使用配置的NSRegularExPRession對象,檢查文本框中數(shù)值型的匹配次數(shù)。    //^[0-9]*$:意思是從行的開頭(表示為^)到結(jié)尾(表示為$)應(yīng)該有數(shù)字集(標(biāo)示為[0-9])中的0或者更多個(gè)字符(表示為*)    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:&regError];            NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];        //如果沒有匹配,就返回錯(cuò)誤和NO    if (numberOfMatches==0) {        if (error != nil) {            NSString *description = NSLocalizedString(@"Input Validation Faild", @"");                        NSString *reason = NSLocalizedString(@"The input can contain only numerical values", @"");                                    NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil];                        NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil];                        NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];                        *error = [NSError errorWithDomain:InputValidationErrorDomain code:1001 userInfo:userInfo];        }        return NO;    }    return YES;}@end

AlphaInputValidator.h

////  AlphaInputValidator.h//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@interface AlphaInputValidator : InputValidator- (BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end

AlphaInputValidator.m

////  AlphaInputValidator.m//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "AlphaInputValidator.h"@implementation AlphaInputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{    NSError *regError = nil;    //使用配置的NSRegularExpression對象,檢查文本框中數(shù)值型的匹配次數(shù)。    //^[0-9]*$:意思是從行的開頭(表示為^)到結(jié)尾(表示為$)應(yīng)該有數(shù)字集(標(biāo)示為[0-9])中的0或者更多個(gè)字符(表示為*)    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:&regError];            NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];        //如果沒有匹配,就返回錯(cuò)誤和NO    if (numberOfMatches==0) {        if (error != nil) {            NSString *description = NSLocalizedString(@"Input Validation Faild", @"");                        NSString *reason = NSLocalizedString(@"The input can contain only letters ", @"");                                    NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil];                        NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil];                        NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];                        *error = [NSError errorWithDomain:InputValidationErrorDomain code:1002 userInfo:userInfo];        }        return NO;    }    return YES;}@end

他們兩個(gè)都是InputValidator的子類。然后再定義一個(gè)CustomTextField:
CustomTextField.h

////  CustomTextField.h//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import <UIKit/UIKit.h>@class InputValidator;@interface CustomTextField : UITextField@property(nonatomic,strong)InputValidator *inputValidator;-(BOOL)validate;@end

CustomTextField.m

////  CustomTextField.m//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "CustomTextField.h"#import "InputValidator.h"@implementation CustomTextField-(BOOL)validate {    NSError *error = nil;    BOOL validationResult = [_inputValidator validateInput:self error:&error];            if (!validationResult) {        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:[error localizedFailureReason] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil];                [alertView show];    }    return validationResult;}@end

最后在ViewController中測試是否完成驗(yàn)證
ViewController.m

////  ViewController.m//  StrategyDemo////  Created by zhanggui on 15/8/7.//  Copyright (c) 2015年 zhanggui. All rights reserved.//#import "ViewController.h"#import "CustomTextField.h"#import "NumericInputValidator.h"#import "AlphaInputValidator.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    _numberTextField.inputValidator = [NumericInputValidator new];    _letterTextField.inputValidator = [AlphaInputValidator new];    // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}#pragma mark - ValidButtonMehtod- (IBAction)validNumAction:(id)sender {    [_numberTextField validate];}- (IBAction)validLetterAction:(id)sender {    [_letterTextField validate];}@end

結(jié)果:當(dāng)我們輸入的不滿足條件的時(shí)候就會顯示提示信息,而滿足條件就不會有任何提示。

附:


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 乐山市| 准格尔旗| 湖州市| 浦东新区| 镇赉县| 合阳县| 四会市| 白银市| 错那县| 光山县| 延吉市| 互助| 隆子县| 荥阳市| 孝义市| 德化县| 满洲里市| 商水县| 新丰县| 拜泉县| 新乡市| 基隆市| 龙山县| 光山县| 云浮市| 界首市| 西宁市| 益阳市| 青神县| 玛纳斯县| 浦东新区| 伊宁市| 淳化县| 河南省| 砚山县| 田林县| 神农架林区| 沁源县| 香港| 乐平市| 鄯善县|