Singleton:在哪里创建实例? [英] Singleton: Where to create instance?

查看:148
本文介绍了Singleton:在哪里创建实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人使用任何偏好或评论...

Does anyone have any preferences or comments about using either ...

static id sharedReactor = nil;

+(id)sharedInstance {
if(sharedReactor == nil) sharedReactor = [[super allocWithZone:NULL] init];
return sharedReactor;
}

static id sharedReactor = nil;

+(void)initialize {
if(sharedRandomReactor == nil) {
sharedRandomReactor = [[super allocWithZone:NULL] init];
}

+(id) sharedInstance {
    return sharedReactor;
}

我认为使用+(void)initialize看起来更加优雅,

To my mind using +(void)initialize seems a lot more elegant, I am just curious what people with more experience than myself think of both approaches?

gary

推荐答案

我刚刚发现一个博客条目从 bbum 重新升级+初始化的可能性可以执行多次,如果一个subClass不实现它,但superClass。只要你保持这个foible心中+(void)初始化可能是最好的选择,特殊性,你需要线程安全,你不想采取使用@synchronized的命中。之后说,如果你只是寻找简单的单例用作共享数据模型,而不是担心线程安全,那么去第一个。

I just spotted a blog entry from bbum regrading the possibility that +initialize can be executed more than once if a subClass does not implement it but the superClass does. As long as you keep this foible in mind +(void)initialize might well be the best option, particularity where you need thread safety and you don't want to take the hit of using @synchronized. After saying that if you just looking for simple singleton to use as a shared data model and are not to worried about thread safety then go with the first one.

这篇关于Singleton:在哪里创建实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆