【原创】开源中国阅读小记 - 2 - 单例

上一篇后面提到DataSingleton是一个单例,看一下具体的源码:

#pragma 单例模式定义
static DataSingleton * instance = nil;
+(DataSingleton *) Instance
{
    @synchronized(self)
    {
        if(nil == instance)
        {
            [self new];
        }
    }
    return instance;
}
+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if(instance == nil)
        {
            instance = [super allocWithZone:zone];
            return instance;
        }
    }
    return nil;
}

这种写法已经足够严谨,同时考虑了内存池以及多线程的特殊情况。Apple的官方示例,但没有包含多线程考虑。

需要注意的是instance的初始化使用了[self new],它是alloc+init的简要写法;调用alloc由于历史原因,objc会默认调用 allocWithZone:,

更为简洁明快的实现方式可以参考:http://eschatologist.net/blog/?p=178

// One way to do this would be to create your singleton instance in +initialize since it will always be run, on a single thread, before any other methods in your class
@implementation SomeManager

static id sharedManager = nil;

+ (void)initialize {
    if (self == [SomeManager class]) {
        sharedManager = [[self alloc] init];
    }
}

+ (id)sharedManager {
    return sharedManager;
}

@end

关于alloc和allocWithZone可以参考:http://www.justinyan.me/post/1306

posted on 2013-06-19 17:30  chenxi_tales  阅读(360)  评论(0编辑  收藏  举报