可可单例和共享实例 [英] Cocoa singleton and shared instances
问题描述
例如,即使UIApplication类允许您访问UIApplication单例,为什么Apple也不将其类作为纯单例呢?
Why do Apple not have their classes as pure singleton, for example, even though the UIApplication class gives you access to the UIApplication singleton, like:
UIApplication *sharedApplication = [UIApplication sharedApplication];
没有什么可以阻止您显式实例化UIApplication实例,例如:
Nothing prevents you from explicitly instantiating a UIApplication instance, like:
UIApplication *newApplication = [[UIApplication alloc] init];
但是,结果是运行时异常.该异常清楚地表明,UIApplication类的一个实例只能在任何一次处于活动状态.
The result, however, is a runtime exception. The exception clearly states that only one instance of the UIApplication class can be alive at any one time.
那么,为什么不通过在默认初始化器中返回相同的实例来获得纯单例呢?
Then why not have pure singleton by returning same instance in the default initializer?
在我的项目上创建单例时,我想问清楚这个问题,以了解哪种方法更好.
I am asking this question to have clarity, when creating singleton on my project, to follow which way is better.
推荐答案
First of all you are right: What Apple calls a singleton is neither a real singleton in the widely accepted definition nor in Apple's definition.
[…]而对于单例类,每个进程只能有一个该类的实例
[…] whereas with a singleton class, there can be only one instance of the class per process
但是,在Swift中实现共享实例非常简单:
However, implementing a shared instance is quite easy in Swift:
class SomeManager {
static let sharedInstance = SomeManager()
}
在Objective-C中,这两种方法(单个实例和共享实例)都是可以实现的,但是共享实例更易于再次实现.
In Objective-C both approaches (singletons and shared instances) are implementable, but a shared instance is easier to implement again.
另一方面,使用共享实例模式没有任何缺点.您应该遵循它.
On the other hand there is no disadvantage of using the shared instance pattern. You should follow it.
顺便说一句:在共享实例的所有情况下,您都不会遇到异常.有些类可让您分配第二个实例,这类似于非法实例.
BTW: You do not get an exception in all cases of shared instances. Some classes let you allocate a second instance, what is akin of illegal.
这篇关于可可单例和共享实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!