iOS設(shè)計模式(一)策略模式

策略模式
  • 概念:定義一系列的算法姑丑,并且將每一個算法封裝起來,算法間可以互相替換.(策略模式基于固定的輸出).
策略模式UML
F3BE4105-4849-4ABD-B7D5-B9758A9B9585.png

聚合關(guān)系 Context把Stategy類引用過來辞友,引用過來目的為了方便調(diào)stategy類的的方法(Context類引用stategy類的話栅哀,簡單的說就時擁有了Stategy的屬性).
stategy是抽象類,(抽象類指的是只有聲明称龙,沒有實(shí)現(xiàn)留拾,所有的繼承都是由繼承的子類contreteStrategyA,contreteStrategyB鲫尊,contreteStrategyC來實(shí)現(xiàn)).


項目(非策略模式&策略模式對比)
  • 非策略模式(寫在一個controller里面實(shí)現(xiàn))
@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 = @"只接受數(shù)字";
   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){
               // 驗證輸入值,確保它輸入的是數(shù)字
               NSString *outputNumber = [self validateNumberInput:textField];
               if (outputNumber) {
                   NSLog(@"-----%@",outputNumber);
       
               } else {
                   NSLog(@"--輸入是空的---");
       
               }
   }
}

- (NSString *)validateLetterInput:(UITextField *)texField
{
   if (texField.text.length == 0) {
       return  nil;
   }
   
   //用正則表達(dá)式 從開頭(表示^)到結(jié)尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azaaaa
   NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
   // NSMatchingAnchored 從開始處進(jìn)行極限匹配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.用正則驗證
       // 從開頭(表示^)到結(jié)尾(表示$)有效數(shù)字集(a-zA-Z)或者是更多(*)的字符  azcccc
       NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
       // NSMatchingAnchored 從開始處進(jìn)行極限匹配
       NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];
       NSString *outLatter = nil;
       // 3.判斷 匹配不符合表示0的話, 就走里面的漏記
       if (numberOfMatches == 0) {
           outLatter = @"不全是數(shù)字,輸入有問題,請重新輸入";
       } else {
           outLatter = @"輸入正取,全是數(shù)字";
       }
       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類成聚合關(guān)系

#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;
    }
    
    //用正則表達(dá)式 從開頭(表示^)到結(jié)尾(表示$)有效字符集(a-zA-Z)或者是更多(*)的字符  azaaaa
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
    // NSMatchingAnchored 從開始處進(jìn)行極限匹配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 = @"請輸入數(shù)字";
        return nil;
    }
    
    // 2.用正則驗證
    // 從開頭(表示^)到結(jié)尾(表示$)有效數(shù)字集(a-zA-Z)或者是更多(*)的字符  azcccc
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:nil];
    
    // NSMatchingAnchored 從開始處進(jìn)行極限匹配
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:NSMatchingAnchored range:NSMakeRange(0, [[textField text] length])];

    // 3.判斷 匹配不符合表示0的話, 就走里面的漏記
    if (numberOfMatches == 0) {
         self.attributeInputStr = @"不全是數(shù)字,輸入有問題,請重新輸入";
    } else {
         self.attributeInputStr = @"輸入正取,全是數(shù)字";
    }
    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 = @"只接受數(shù)字";
    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
  • 優(yōu)點(diǎn):可以精簡if-else的代碼痴柔,解藕性高,可復(fù)用性高.
  • 缺點(diǎn):知道固有的輸入,在固定的場景下使用疫向,代碼量大咳蔚,分類多.
    demo地址:https://github.com/defuliu/StrategyPatterns
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市搔驼,隨后出現(xiàn)的幾起案子谈火,更是在濱河造成了極大的恐慌,老刑警劉巖舌涨,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件糯耍,死亡現(xiàn)場離奇詭異,居然都是意外死亡囊嘉,警方通過查閱死者的電腦和手機(jī)温技,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扭粱,“玉大人荒揣,你說我怎么就攤上這事『干玻” “怎么了系任?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長虐块。 經(jīng)常有香客問我俩滥,道長,這世上最難降的妖魔是什么贺奠? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任霜旧,我火速辦了婚禮,結(jié)果婚禮上儡率,老公的妹妹穿的比我還像新娘挂据。我一直安慰自己以清,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布崎逃。 她就那樣靜靜地躺著掷倔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪个绍。 梳的紋絲不亂的頭發(fā)上勒葱,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天,我揣著相機(jī)與錄音巴柿,去河邊找鬼凛虽。 笑死,一個胖子當(dāng)著我的面吹牛广恢,可吹牛的內(nèi)容都是我干的凯旋。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼钉迷,長吁一口氣:“原來是場噩夢啊……” “哼瓦阐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起篷牌,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎踏幻,沒想到半個月后枷颊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡该面,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年夭苗,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片隔缀。...
    茶點(diǎn)故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡题造,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出猾瘸,到底是詐尸還是另有隱情界赔,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布牵触,位于F島的核電站淮悼,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏揽思。R本人自食惡果不足惜袜腥,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望钉汗。 院中可真熱鬧羹令,春花似錦鲤屡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至癌刽,卻和暖如春役首,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背显拜。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工衡奥, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人远荠。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓矮固,卻偏偏與公主長得像,于是被迫代替她去往敵國和親譬淳。 傳聞我的和親對象是個殘疾皇子档址,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 參考資料:菜鳥教程之設(shè)計模式 設(shè)計模式概述 設(shè)計模式(Design pattern)代表了最佳的實(shí)踐,通常被有經(jīng)驗...
    Steven1997閱讀 1,176評論 1 12
  • 設(shè)計模式基本原則 開放-封閉原則(OCP)邻梆,是說軟件實(shí)體(類守伸、模塊、函數(shù)等等)應(yīng)該可以拓展浦妄,但是不可修改尼摹。開-閉原...
    西山薄涼閱讀 3,808評論 3 14
  • 設(shè)計模式匯總 一、基礎(chǔ)知識 1. 設(shè)計模式概述 定義:設(shè)計模式(Design Pattern)是一套被反復(fù)使用剂娄、多...
    MinoyJet閱讀 3,949評論 1 15
  • 真誠的蠢涝,TNANKS。 個人Github-23種設(shè)計模式案例鏈接 創(chuàng)建型模式 工廠模式 工廠模式(Factory ...
    水清_木秀閱讀 26,087評論 11 204
  • 凌晨四點(diǎn)到中午11點(diǎn)阅懦,下午三點(diǎn)到晚七點(diǎn)和二,這是爸爸夏季在地里勞作的時間表,可以說除了吃飯睡覺都在地里耳胎。 旁邊那家的嬸...
    劉秀玲閱讀 2,290評論 156 110