[英]Replace constructor with factory method
在Java中,工厂构造函数可以在抽象超类中定义,例如:
public static Parent createChildFromType(int type) {
switch (type) {
case 0:
return new Child1();
case 1:
return new Child2();
default:
throw new Exception();
}
}
但是,在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
Child1.h
和Child2.h
都具有#import "Parent.h"
因为我想事先不知道我要调用哪个子类的方式来调用someAbstractMethod
:
-(void)someVoodooMethod:(int) type {
Parent *child = [Parent createChildFromType: type];
[child someAbstractMethod];
}
我有一个预感,这是由于@implementation Parent
中有多余的#import "Parent.h"
@implementation Parent
,但是我还没有想到解决它的方法。 有什么建议么?
编辑:
我想应该包含Child1.h
的代码:
#import "Parent.h"
@interface Child1 : Parent
@end
和Child2.h
#import "Parent.h"
@interface Child2 : Parent
@end
您需要在子项中声明父项。
这是解释obj-c中的前向声明的链接: Objective-C:前向类声明
只需添加
@class Parent;
在child1.h中,child2.h。
在child1.m和child2.m中,您可以包含Parent.h
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.