iOS能否实现单例继承
Can Singleton Inheritance be achieved in iOS
我有几个 class 应该继承自某些 A
class。
他们每个人都应该是一个单身人士。
这能实现吗?
是的。我不确定您是否熟悉 Obj-C 单例模式,但这里有一个指南:
http://www.galloway.me.uk/tutorials/singleton-classes/
subclassing 应该不会再有任何并发症了。只需创建一个单例的子class,它也将继承它的单例能力。我认为每个 subclass 都会创建它自己的唯一单例,但如果没有,请覆盖单例生成器,使其对于该 subclass.
是唯一的
请记住,单例在 iOS 上正在失宠,因此应谨慎使用。我尝试仅在尝试创建多个实例根本不可能时才使用它们(即 class 用于访问必须由 class 专门保留的硬件资源。)
这种单例模式的实现允许继承:
+ (instancetype)sharedInstance {
static dispatch_once_t once;
static NSMutableDictionary *sharedInstances;
dispatch_once(&once, ^{ /* This code fires only once */
// Creating of the container for shared instances for different classes
sharedInstances = [NSMutableDictionary new];
});
id sharedInstance;
@synchronized(self) { /* Critical section for Singleton-behavior */
// Getting of the shared instance for exact class
sharedInstance = sharedInstances[NSStringFromClass(self)];
if (!sharedInstance) {
// Creating of the shared instance if it's not created yet
sharedInstance = [self new];
sharedInstances[NSStringFromClass(self)] = sharedInstance;
}
}
return sharedInstance;
}
你永远不会继承单例 class。这以一种糟糕的方式完全打破了单身人士的概念。
有多个单例class继承自同一个基class:没问题。事实上,大多数单例都有通用的 superclass NSObject,但你可以使用任何其他 superclass。
我有几个 class 应该继承自某些 A
class。
他们每个人都应该是一个单身人士。
这能实现吗?
是的。我不确定您是否熟悉 Obj-C 单例模式,但这里有一个指南: http://www.galloway.me.uk/tutorials/singleton-classes/
subclassing 应该不会再有任何并发症了。只需创建一个单例的子class,它也将继承它的单例能力。我认为每个 subclass 都会创建它自己的唯一单例,但如果没有,请覆盖单例生成器,使其对于该 subclass.
是唯一的请记住,单例在 iOS 上正在失宠,因此应谨慎使用。我尝试仅在尝试创建多个实例根本不可能时才使用它们(即 class 用于访问必须由 class 专门保留的硬件资源。)
这种单例模式的实现允许继承:
+ (instancetype)sharedInstance {
static dispatch_once_t once;
static NSMutableDictionary *sharedInstances;
dispatch_once(&once, ^{ /* This code fires only once */
// Creating of the container for shared instances for different classes
sharedInstances = [NSMutableDictionary new];
});
id sharedInstance;
@synchronized(self) { /* Critical section for Singleton-behavior */
// Getting of the shared instance for exact class
sharedInstance = sharedInstances[NSStringFromClass(self)];
if (!sharedInstance) {
// Creating of the shared instance if it's not created yet
sharedInstance = [self new];
sharedInstances[NSStringFromClass(self)] = sharedInstance;
}
}
return sharedInstance;
}
你永远不会继承单例 class。这以一种糟糕的方式完全打破了单身人士的概念。
有多个单例class继承自同一个基class:没问题。事实上,大多数单例都有通用的 superclass NSObject,但你可以使用任何其他 superclass。