代码重构2个重复方法

时间:2010-11-09 16:55:31

标签: iphone objective-c refactoring nsmutablearray

基本上我有两种功能相似的方法。唯一的区别是不同的类容器。我想要实现的是统一这两种方法,并以某种方式让容器变得动态。

这里有两种方法:

-(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 个答案:

答案 0 :(得分:1)

将该类设为参数。

-(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]];
}

答案 1 :(得分:1)

或者您可以使用工厂模式:


-(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];
}