减少项目中的if else 或者switch

386 阅读1分钟

1、表驱动法 通过字段映射关系

2、策略模式 同一个对象调用同一个方法,实现不同

// 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];

3、工厂模式 不同对象调用同一个方法,实现不同

4、反射 反射的优点:松耦合,可以对象之间的依赖,实现很多原先比较麻烦的场景。 反射的缺点:性能略微低,通过字符串匹配内存中的实现,效率没有直接引用高。 代码可读性低,对象之间的一些逻辑不能直观体现。

//注入类
    // Default case. Create dynamic subclass.
    const char *subclassName = [className stringByAppendingString:AspectsSubclassSuffix].UTF8String;
    Class subclass = objc_getClass(subclassName);

    if (subclass == nil) {
        subclass = objc_allocateClassPair(baseClass, subclassName, 0);
        ...
    }

//注入方法
class_addMethod(class, selector,  method_getImplementation(method),  method_getTypeEncoding(method));

5、多态 没有继承就没有多态,父类类型的指针指向子类对象 而狗和猫实际上都继承于动物这个类,在这里就可以使用多态来简化代码了。 我们只需要把函数的参数写成是Animal *类型的,那么Dog和Cat类型的对象就都可以传入进来,调用的时候直接强转参数类型就可以了。

 Printer *p1 = [[ColorPrinter alloc] init];  
 Printer *p2 = [[BlackPrinter alloc] init];  
 [person doPrint:p1];  
 [person doPrint:p2];