初始化单身人士的不同方式 [英] Different ways to initialize singletons

查看:117
本文介绍了初始化单身人士的不同方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#和Java,我基本上看到每个人初始化单例的方式:

Working in C# and Java, I've seen basically one way everybody initializes singletons:

static obj _inst = null;

obj getInstance() {
  if (_inst == null) {
    _inst = new obj();
  }
  return _inst;
}

现在,当我转向iPhone的Objective-C时,每当我看到代码示例,我看到基本相同的事情:

Now, when I move to Objective-C for the iPhone, whenever I see code samples, I see basically the same thing:

static obj _inst = nil;

+ (obj *) sharedObj {
  if (!_inst) {
    _inst = [[obj alloc] init];
  }
  return _inst;
}

有一个类方法 + initialize 在Objective-C运行时使用它之前调用它。有什么理由我不能用它来创造我的单身人士吗?

There's a class method +initialize that's called on every class in the Objective-C runtime before it's used. Is there any reason I couldn't use that to create my singletons?

static obj _inst = nil;

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

+ (obj *) sharedObj {
  return _inst;
}

当我在我的代码中尝试它时,它工作正常,它摆脱它在每次访问之前检查它是否存在。我有什么理由不这样做单身吗?

It works just fine when I try it in my code, and it gets rid of checking to see if it exists every time before it's accessed. Is there any reason I shouldn't create singletons this way?

推荐答案

据我所知 + initialize 是这样做的方法。 Peter Hosey 建议其他几个捕获(内部) -init -allocWithZone:)以确保无法实例化该类的多个实例。从而使它成为一个真正的单例类,而不仅仅是一个带有指向其中特定实例的指针的类。

As far as I'm concerned +initialize is the way to do it. Peter Hosey suggests a couple of other catches (inside -init and -allocWithZone:) to make sure you can't instantiate more than one instance of the class, ever. Thus making it a true singleton class and not just a class with a pointer to a particular instance of itself within it.

这篇关于初始化单身人士的不同方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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