简体   繁体   中英

Replace constructor with factory method

In Java, a factory constructor can be defined in an abstract superclass like:

public static Parent createChildFromType(int type) {
    switch (type) {
        case 0:
            return new Child1();
        case 1:
            return new Child2();
        default:
            throw new Exception();
    }
}

But, in Objective-C, I'm getting a 'No known class method for selector "alloc"' for case 1 :

#import "Child1.h"
#import "Child2.h"

@implementation Parent

+(id)createChildFromType:(int)type {
    switch (type) {
        case 0:
            return [[Child1 alloc]init];
        case 1:
            return [[Child2 alloc]init];
        default:
            @throw [NSException exceptionWithName:NSInternalInconsistencyException 
                    reason:@"Invalid subclass type." 
                    userInfo:nil];
     }
}

-(void)someAbstractMethod {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException 
                    reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", 
                            NSStringFromSelector(_cmd)] 
                    userInfo:nil];
}

@end

Both Child1.h and Child2.h have #import "Parent.h" because I'd like to make a call to someAbstractMethod , without knowing beforehand, which subclass I'm calling it on:

-(void)someVoodooMethod:(int) type {
    Parent *child = [Parent createChildFromType: type];
    [child someAbstractMethod];
}

I have a hunch that it's because of the redundant #import "Parent.h" in the @implementation Parent , but I haven't thought of a way around it. Any suggestions?

EDIT:

I suppose the code for Child1.h should be included:

#import "Parent.h"
@interface Child1 : Parent
@end

And Child2.h

#import "Parent.h"
@interface Child2 : Parent
@end

You need to forward declare parent in the childs.

Here's a link explaining forward declaration in obj-c: Objective-C: Forward Class Declaration

Just add

@class Parent; 

In the child1.h , child2.h.

In child1.m , child2.m you can include Parent.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM