舉例講解iOS應(yīng)用開發(fā)中對設(shè)計(jì)模式中的策略模式的使用
策略模式是一種常見的軟件設(shè)計(jì)模式,這里簡單得介紹一下策略模式并用IOS簡單實(shí)現(xiàn)一下。
所謂的策略模式,顧名思義是要采用不同的策略的。一般來說,在不同的情況下,處理某一個問題的方法也不一樣。比如說對字符串的排序和對數(shù)字的排序,雖然用的都是快排,但是顯然不可能使用一段通用的代碼。有人說java里面的compareTo可以做到,但如果考慮這么一個問題:同樣是出門旅行,老年人身體虛弱,需要大量的休息,而孩子則是精力充沛,希望玩到更多的景點(diǎn)。如何在同一模式下表達(dá)以上信息、采用合理的設(shè)計(jì)模式進(jìn)行封裝而不是大量重寫類似的代碼,就需要學(xué)習(xí)并采用策略模式。
例子
該例子主要利用策略模式來判斷UITextField是否滿足輸入要求,比如輸入的只能是數(shù)字,如果只是數(shù)字就沒有提示,如果有其他字符則提示出錯。驗(yàn)證字母也是一樣。
首先,我們先定義一個抽象的策略類IputValidator。代碼如下:
InputValidator.h
#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
#import "InputValidator.h"
@implementation InputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error
{
if (error) {
*error = nil;
}
return NO;
}
@end
這個就是一個策略基類,然后我們?nèi)?chuàng)建兩個子類NumericInputValidator和AlphaInputValidator。具體代碼如下:
NumericIputValidator.h
#import "InputValidator.h"
@interface NumericInputValidator : InputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;
@end
NumericIputValidator.m
#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或者更多個字符(表示為*)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];
//如果沒有匹配,就返回錯誤和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
#import "InputValidator.h"
@interface AlphaInputValidator : InputValidator
- (BOOL)validateInput:(UITextField *)input error:(NSError **)error;
@end
AlphaInputValidator.m
#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或者更多個字符(表示為*)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];
//如果沒有匹配,就返回錯誤和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
他們兩個都是InputValidator的子類。然后再定義一個CustomTextField:
CustomTextField.h
#import <UIKit/UIKit.h>
@class InputValidator;
@interface CustomTextField : UITextField
@property(nonatomic,strong)InputValidator *inputValidator;
-(BOOL)validate;
@end
CustomTextField.m
#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
#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)我們輸入的不滿足條件的時候就會顯示提示信息,而滿足條件就不會有任何提示。
優(yōu)點(diǎn)
- 策略模式是一種定義一系列算法的方法,從概念上來看,所有這些算法完成的都是相同的工作,只是實(shí)現(xiàn)不同,它可以以相同的方式調(diào)用所有的算法,減少了各種算法類與使用算法類之間的耦合。
- 策略模式的Stategy類層次為Context定義了一些列的可供重用的算法或行為。繼承有助于析取出算法中的公共功能。
- 策略模式的優(yōu)點(diǎn)是簡化了單元測試,因?yàn)槊總€算法都有自己的類,可以通過自己的接口單獨(dú)測試。
使用場景
- 一個類在其操作中使用多個條件語句來定義許多行為。我們可以把相關(guān)的條件分支移到他們自己的策略類中
- 需要算法的各種變體
- 需要避免把復(fù)雜的、與算法相關(guān)的數(shù)據(jù)結(jié)構(gòu)暴露給客戶端
總結(jié)
再總結(jié)一下策略方法的實(shí)現(xiàn),本質(zhì)上就是需要完成一個事情(出行),但是并不清楚需要使用怎樣的策略,所以封裝出一個函數(shù),能夠把需要的策略(young OR old)作為參數(shù)傳遞進(jìn)來,并且使用相應(yīng)的策略完成這個事件的處理。
最后簡單談一談個人對于策略模式和面向?qū)ο笾卸鄳B(tài)的思想的理解,首先多態(tài)是高層次,高度抽象的概念,獨(dú)立于語言之外,是面向?qū)ο笏枷氲木?,而策略模式只是一種軟件設(shè)計(jì)模式,相對而言更加具體,而且具體實(shí)現(xiàn)依賴于具體的編程語言,比如OC和java的實(shí)現(xiàn)方法并不相同,是language-dependent的。其次,多態(tài)更多強(qiáng)調(diào)的是,不同的對象調(diào)用同一個方法會得到不同的結(jié)果,而策略模式更多強(qiáng)調(diào)的是,同一個對象(事實(shí)上這個對象本身并不重要)在不同情況下執(zhí)行不同的方法,而他們的實(shí)現(xiàn)方式又是高度類似的,即共享同一個父類并且各自重寫父類的方法。
以上觀點(diǎn)純屬個人愚見,歡迎大牛指正,互相交流。
- 詳解iOS App設(shè)計(jì)模式開發(fā)中對于享元模式的運(yùn)用
- iOS App設(shè)計(jì)模式開發(fā)中對建造者模式的運(yùn)用實(shí)例
- iOS App設(shè)計(jì)模式開發(fā)中對迭代器模式的使用示例
- iOS App的設(shè)計(jì)模式開發(fā)中對State狀態(tài)模式的運(yùn)用
- 解析iOS應(yīng)用開發(fā)中對設(shè)計(jì)模式中的抽象工廠模式的實(shí)現(xiàn)
- 詳解iOS應(yīng)用開發(fā)中使用設(shè)計(jì)模式中的抽象工廠模式
- 實(shí)例解析設(shè)計(jì)模式中的外觀模式在iOS App開發(fā)中的運(yùn)用
- 設(shè)計(jì)模式開發(fā)中的備忘錄模式在iOS應(yīng)用開發(fā)中的運(yùn)用實(shí)例
- 深入解析設(shè)計(jì)模式中的裝飾器模式在iOS應(yīng)用開發(fā)中的實(shí)現(xiàn)
- iOS App設(shè)計(jì)模式開發(fā)中策略模式的實(shí)現(xiàn)示例
- iOS App使用設(shè)計(jì)模式中的模板方法模式開發(fā)的示例
- iOS App設(shè)計(jì)模式開發(fā)中對interpreter解釋器模式的運(yùn)用
相關(guān)文章
iOS10 App適配權(quán)限 Push Notifications 字體Frame 遇到的問題
這篇文章主要介紹了iOS10 App適配權(quán)限 Push Notifications 字體Frame 遇到的問題,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09iOS利用UIBezierPath + CAAnimation實(shí)現(xiàn)路徑動畫效果
在iOS開發(fā)中,制作動畫效果是最讓開發(fā)者享受的環(huán)節(jié)之一,這篇文章主要給大家介紹了關(guān)于iOS利用UIBezierPath + CAAnimation實(shí)現(xiàn)路徑動畫效果的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10iOS中UITextField實(shí)現(xiàn)過濾選中狀態(tài)拼音的代碼
這篇文章主要介紹了iOS中UITextField實(shí)現(xiàn)過濾選中狀態(tài)拼音的代碼,需要的朋友可以參考下2018-01-01iOS開發(fā)中Quartz2D繪圖路徑的使用以及條紋效果的實(shí)現(xiàn)
這篇文章主要介紹了iOS開發(fā)中Quartz2D繪圖路徑的使用以及條紋效果的實(shí)現(xiàn),代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11