效果
说明
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,还有,实现细节暴露出来,维护困难 -_-!!)
时间: 2024-11-03 22:10:57