简体   繁体   English

用工厂方法替换构造函数

[英]Replace constructor with factory method

In Java, a factory constructor can be defined in an abstract superclass like: 在Java中,工厂构造函数可以在抽象超类中定义,例如:

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 : 但是,在Objective-C中,我遇到了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: Child1.hChild2.h都具有#import "Parent.h"因为我想事先不知道我要调用哪个子类的方式来调用someAbstractMethod

-(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. 我有一个预感,这是由于@implementation Parent中有多余的#import "Parent.h" @implementation Parent ,但是我还没有想到解决它的方法。 Any suggestions? 有什么建议么?

EDIT: 编辑:

I suppose the code for Child1.h should be included: 我想应该包含Child1.h的代码:

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

And Child2.h 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 这是解释obj-c中的前向声明的链接: Objective-C:前向类声明

Just add 只需添加

@class Parent; 

In the child1.h , child2.h. 在child1.h中,child2.h。

In child1.m , child2.m you can include Parent.h 在child1.m和child2.m中,您可以包含Parent.h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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