代码之家  ›  专栏  ›  技术社区  ›  Frank

两个重复方法的代码重构

  •  1
  • Frank  · 技术社区  · 14 年前

    基本上我有两个功能相似的方法。唯一的区别是类容器不同。我试图实现的是将这两种方法统一起来,并使容器具有动态性。

    -(NSMutableArray*) parseRequest:(NSArray*)elements {
        NSMutableArray *currentStruct = [NSMutableArray array];
        for (id element elemets) {
            // This is where the difference is
            FriendRequest *friend = [[FriendRequest alloc] init];
    
            if(nickname != nil) {
                friend.nickname = [element objectAtIndex:0];
            }
            [currentStruct addObject:friend];   
            [friend release];
    
        }
        return currentStruct;
    }
    

    第二:

    -(NSMutableArray*) parseRequest:(NSArray*)elements {
        NSMutableArray *currentStruct = [NSMutableArray array];
        for (id element elemets) {
            // This is where the difference is
            Friend *friend = [[Friend alloc] init];
    
            if(nickname != nil) {
                friend.nickname = [element objectAtIndex:0];
            }
            [currentStruct addObject:friend];   
            [friend release];
    
        }
        return currentStruct;
    }
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   kennytm    14 年前

    将该类设置为参数。

    -(NSMutableArray*) parseRequest:(NSArray*)elements withClass:(Class)friendClass {
        NSMutableArray *currentStruct = [NSMutableArray array];
        for (id element elemets) {
            // This is where the difference is
            id friend = [[friendClass alloc] init];  // <---
    
            if(nickname != nil) {
                [friend setNickname:[element objectAtIndex:0]];
            }
            [currentStruct addObject:friend];   
            [friend release];
    
        }
        return currentStruct;
    }
    
    ...
    
    -(NSMutableArray*) parseRequest:(NSArray*)elements {
      return [self parseRequest:elements withClass:[Friend class]];
    }
    
        2
  •  1
  •   Alejandro    14 年前

    或者可以使用工厂模式:

    
    -(NSMutableArray*) parseRequest:(NSArray*)elements factory:(SEL)factory {
        NSMutableArray *currentStruct = [NSMutableArray array];
        for (id element elemets) {
            NSObject *friend = [self performSelector:factory];
    
            if(nickname != nil) {
                [friend performSelector:@selector(setNickname) withObject:[element objectAtIndex:0]];
            }
            [currentStruct addObject:friend];
    
        }
        return currentStruct;
    }
    
    -(Friend*) friendFactory {
        return [[[Friend alloc] init] autorelease];
    }