通常这是通过Factory完成的。
如果您希望工厂成为基类的一部分,那很好,但将来可能会导致问题。在 Objective C 中,类方法是好的工厂。
+ (Vehicle *)vehicleWithDictionary:(NSDictionary *)dict
{
if ([[dict objectForKey:kVehicleType] isEqualToString:@"TwoWheeler"]) {
return [[[TwoWheeler alloc] initWithDictionary:dict] autorelease];
} else if ([[dict objectForKey:kVehicleType] isEqualToString @"FourWheeler"]) {
return [[[FourWheeler alloc] initWithDictionary:dict] autorelease];
} else {
return [[[Vehicle alloc] initWithDictionary:dict] autorelease];
}
}
工厂可以是 Vehicle 类的一部分并按原样使用。
// Instead of [[Vehicle alloc] initWithDictionary:dict]
Vehicle *vehicle = [Vehicle vehicleWithDictionary:dict];
更新
我想出了一种方法来做被问到的事情。让它成为一个光辉的例子,说明为什么它是一个坏主意以及为什么你永远不应该这样做。
- (id)initWithDictionary:(NSDictionary *)dict
{
self = [super init];
if (self) {
// If override is in the dictionary, then it mustn't try to call the subclass.
if (![dict objectForKey:kOverride]) {
NSMutableDictionary *overrideDict = [NSMutableDictionary dictionaryWithDictionary:dict];
[overrideDict setObject:@"override" forKey:kOverride];
if ([[dict objectForKey:kVehicleType] isEqualToString:@"TwoWheeler"]) {
[self release];
return [[[TwoWheeler alloc] initWithDictionary:overrideDict] autorelease];
} else if ([[dict objectForKey:kVehicleType] isEqualToString @"FourWheeler"]) {
[self release];
return [[[FourWheeler alloc] initWithDictionary:overrideDict] autorelease];
}
}
// init as normal
}
return self;
}