我有一个Objective-C类的集合,这些类在各种不同的深度被各种不同的类子类化。初始化整个对象(所有子类的初始化函数都已完成)后,我需要运行“更新缓存”方法,然后根据需要由子类重写。
我的问题:
由于类树具有多种不同的继承深度,因此没有一个地方可以放置[self UpdateCache],并且可以确保没有未初始化的子类。唯一可能的解决方案是在每个类初始化之后调用[super init],以便始终将父类调用为最后一个。我要避免这种情况,因为这违反了编写Objective-C的所有准则。有没有解决这个问题的解决方案?
这是一些示例代码:
@interface ClassA : NSObject
-(void)UpdateCache
@end
@interface ClassB : ClassA
-(void)UpdateCache
@end
@interface ClassC : ClassB
-(void)UpdateCache
@end
现在,对于实现,我们需要以某种方式在知道所有子类都已初始化之后,不管哪个类已初始化,都调用UpdateCahce。
@implementation A
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] here would make it be called prior to
// B and C's complete init function from being called.
}
}
-(void)UpdateCache
{
}
@end
@implementation B
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] would result in UpdateChache not being
// called if you initialized an instance of Class A
}
}
-(void)UpdateCache
{
[super UpdateCache];
}
@end
@implementation C
-(id)init
{
if(self = [super init])
{
// Placing [self UpdateCache] would result in UpdateChache not
//being called if you initialized an instance of Class A or B
}
}
-(void)UpdateCache
{
[super UpdateCache];
}
@end
最佳答案
您的子类是否需要唯一的init方法签名? (例如,初始化对象所需的子类特定参数),否则,遵循简单的类似工厂的设计模式可能会很好。
添加父/基类的示例:
+(id)buildSelf {
YourParentClass* obj = [[[self alloc] init] autorelease];
if (obj) {
[obj updateCache];
}
return obj;
}
如果需要,向其添加参数,以供所有子类使用。
同样,如果您的子类需要支持唯一的init方法签名,那么它将不能很好地工作。