[iOS]使用策略模式来去除繁琐的if-else
2019-04-17 本文已影响0人
豆豆哥哥
image.png
那么用策略模式如何实现呢?也是一段非常简单的代码:
NSDictionary *dict =@{
@"类型1" : @001,
@"类型2" : @002,
@"类型3" : @003
};
NSInteger id = dict[type];//type 为类型1,类型2,类型3
eg
周一打篮球
周二逛街
周三洗衣服
周四打游戏
周五唱歌
周六看电影
周末爬山
我们用分支来写,应该是这样的:
if(day == 周一){
result = [xiaoming playBasketball];
}else if (day == 周二){
result = [xiaoming shopping];
}else if (day == 周三){
result = [xiaoming washClothes];
}else if(...) {
...
}//很烦,写不下去了
NSLog(@"xiaoming 今天%@",result);
用策略:
// 1.将复杂的业务逻辑包装成invocation,这里传入的每天做的事,例如playBasketball
- (NSInvocation *)invocationWithMethod:(SEL)selector{
NSMethodSignature*signature = [CurrentClass instanceMethodSignatureForSelector:@selector(selector)];
NSInvocation*invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = @selector(selector);
return invocation;
}
// 2.将每天做的事进行整合
- (NSDictionary *)Strategies{
NSDictionary *Strategies = @{
@"day1" : [self invocationWithMethod:@selector(playBasketball)],
@"day2" : [self invocationWithMethod:@selector(shopping)],
@"day3" : [self invocationWithMethod:@selector(washClothes)],
@"day4" : [self invocationWithMethod:@selector(playGames)],
@"day5" : [self invocationWithMethod:@selector(sing)],
@"day6" : [self invocationWithMethod:@selector(watchMovie)],
@"day7" : [self invocationWithMethod:@selector(climbing)],
};
return Strategies;
}
// 3.找出小明哪天做的事
NSInvocation *doWhat = self.Strategies[whichDay];
[doWhat invoke];
eg:例子
image.png//平时解答
- (BOOL)isValid:(NSString *)str{
char array[64] ;
NSInteger location = 0;
NSInteger len = str.length;
if(len < 1){
return NO;
}
for (int i = 0; i < len; i++) {
char c = [str characterAtIndex:i];
if(c == '(' || c == '{' || c == '['){
array[location] = c;
location ++;
}else{
if (location == 0 )return NO;
char tmpLeft = array[location -1];
if (tmpLeft == '(' && c != ')') return NO;
if (tmpLeft == '{' && c != '}') return NO;
if (tmpLeft == '[' && c != ']') return NO;
location --;
}
}
return location == 0 ? YES : NO;
}
用策略
- (BOOL)isValid2:(NSString *)str{
char array[64] ;
NSInteger location = 0;
NSInteger len = str.length;
NSDictionary *dict = @{@"(":@")",
@"{":@"}",
@"[":@"]"
};
if(len < 1){
return NO;
}
for (int i = 0; i < len; i++) {
char c = [str characterAtIndex:i];
NSString *strTmp = [[NSString alloc] initWithCString:c];
if([dict.allKeys containsObject:strTmp]){
array[location] = c;
location ++;
}else{
if (location == 0 )return NO;
NSString * tmpLeft = [[NSString alloc] initWithCString: array[location -1]];
if ( strTmp != dict[tmpLeft]) return NO;
location --;
}
}
return location == 0 ? YES : NO;
}