程序开发(Objective-C)中,经常要用到单例,其创建代码如下:
static Car *sharedInstance = nil;
#pragma mark Single instance
+ (Car *)sharedInstance {
if (!sharedInstance) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance;
}
}
return nil;
}
说明:
- 覆盖allocWithZone:方法的目的是为了防止任何类创建第二个实例;
- @synchronized指令防止多线程同时调用该代码块;
Objective-C单例模式深入解析
本文详细介绍了Objective-C中单例模式的实现原理及优化措施,包括如何使用同步指令防止多线程并发创建多个实例,以及覆盖allocWithZone:方法以确保只有一个实例被创建。
217

被折叠的 条评论
为什么被折叠?



