[英]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.