標籤:
iOS設計模式 - 策略
效果
說明
1. 把解決相同問題的演算法抽象成策略(相同問題指的是輸入參數相同,但根據演算法不同輸出參數會有差異)
2. 策略被封裝在對象之中(是對象內容的一部分),策略改變的是對象的內容.如果從外部擴充了對象的行為,就不叫策略模式,而是裝飾模式.
3. 策略模式可以簡化複雜的判斷邏輯(if - else)
4. 如果對物件導向基本原理以及設計模式基本原理不熟悉,本教程會變得難以理解.
源碼
https://github.com/YouXianMing/StrategyPattern
//// InputValidator.h// StrategyPattern//// Created by YouXianMing on 15/7/26.// Copyright (c) 2015年 YouXianMing. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>#define EMPTY_INPUT @"輸入為空白"@interface InputValidator : NSObject/** * 抽象策略 * * @param input 當前輸入textField * * @return 輸入驗證是否合法 */- (BOOL)validateInput:(UITextField *)input;/** * 錯誤資訊 */@property (nonatomic, strong) NSString *errorMessage;@end
//// InputValidator.m// StrategyPattern//// Created by YouXianMing on 15/7/26.// Copyright (c) 2015年 YouXianMing. All rights reserved.//#import "InputValidator.h"@implementation InputValidator- (BOOL)validateInput:(UITextField *)input { return NO;}@end
//// CustomField.h// StrategyPattern//// Created by YouXianMing on 15/7/26.// Copyright (c) 2015年 YouXianMing. All rights reserved.//#import <UIKit/UIKit.h>#import "InputValidator.h"@interface CustomField : UITextField/** * 抽象策略 */@property (nonatomic, strong, readonly) InputValidator *inputValidator;/** * 初始化textField * * @param frame * @param inputValidator 驗證策略 * * @return 執行個體對象 */- (instancetype)initWithFrame:(CGRect)frame withInputValidator:(InputValidator *)inputValidator;/** * 對應於具體策略的傳回值 * * @return 是否合格 */- (BOOL)validate;@end
//// CustomField.m// StrategyPattern//// Created by YouXianMing on 15/7/26.// Copyright (c) 2015年 YouXianMing. All rights reserved.//#import "CustomField.h"@interface CustomField ()/** * 抽象策略 */@property (nonatomic, strong) InputValidator *inputValidator;@end@implementation CustomField#pragma mark - 初始化- (instancetype)initWithFrame:(CGRect)frame withInputValidator:(InputValidator *)inputValidator { self = [super initWithFrame:frame]; if (self) { [self setup]; // 持有inputValidator self.inputValidator = inputValidator; } return self;}- (void)setup { UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, self.frame.size.height)]; self.leftView = leftView; self.leftViewMode = UITextFieldViewModeAlways; self.font = [UIFont fontWithName:@"Avenir-Book" size:12.f]; self.layer.borderWidth = 0.5f;}- (BOOL)validate { return [self.inputValidator validateInput:self];}@end
分析
策略模式對比(抽象類別與具體實現的詳細對比)
策略被封裝在對象之中(是對象內容的一部分),策略改變的是對象的內容的
簡化了 if - else 操作(按照以前的寫法,有幾個TextField判斷,就得寫幾個if - else,還有,實現細節暴露出來,維護困難 -_-!!)
iOS設計模式 - 策略