我们的静态库之一中有一个单例类。它是一个单例,因为我们希望能够始终“记住”它的状态。本质上它是一个用户管理单例。
它有一个属性User *user
它有诸如- (void)authenticateUser
.
我们希望将其交付给想要创建自己的客户- (void)authenticateUser
方法。为此,我设想他们会延长UserManager
类并覆盖该方法。
然而,由于它是单例,因此它具有以下方法:- (id)sharedInstance
和一个习惯alloc
方法。它们看起来都是这样的:
static UserManager *_sharedInstance = nil;
+ (id)sharedInstance {
@synchronized([UserManager class]) {
if(!_sharedInstance){
id temp = [[self alloc] init];
[temp class];
}
return _sharedInstance;
}
return nil;
}
+ (id)alloc {
@synchronized([UserManager class]) {
NSAssert(_sharedInstance == nil, @"Attempted to allocate a second instance of a singleton");
_sharedInstance = [super alloc];
return _sharedInstance;
}
return nil;
}
那么考虑到这一点,是否可以子类化并扩展它UserManager
班级?我可以创建一个ChildUserManager
哪个覆盖函数?或者我是否必须重写这些单例方法来处理“新”子类?
有什么方法可以修改这些方法,以便第三方可以轻松扩展此类?
Thanks
更好的单例模式:
// UserManager.h
#import <Foundation/Foundation.h>
@interface UserManager : NSObject
+(instancetype)sharedInstance;
// clue for improper use (produces compile time error)
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
@end
// UserManager.m
#import "UserManager.h"
@implementation UserManager
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
return [super init];
}
@end
如果您子类化,单个实例将被设置为首先调用的任何内容,例如:
[Animal sharedInstance]; // instance set to Animal
[[Cow sharedInstance] moo]; // unknown selector 'moo' because the instance is Animal
仅此一项就可以工作:
[[Cow sharedInstance]moo];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)