HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何使我的单例类可扩展?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我们在一个静态库中有一个单例类.这是一个单身人士,因为我们希望能够随时“记住”其状态.从本质上讲,它是一个用户管理单例.

它有一个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吗?或者我是否必须重写这些单例方法来处理“新”子类?

有什么方法可以修改这些方法,以便第三方可以轻松扩展这个类?

谢谢

解决方法

Beter设计将使用COR_864_11845@position然后继承.声明协议AuthenticationDelegate

@protocol AuthenticationDelegate
@optional
-(void) authenticateUser:(User*)inUser;
@end

在UseRMANager中有一个属性,认情况下指向UseRMANager.

@class UseRMANager : NSObject <AuthenticationDelegate> {
    ......
} 

@property (assign) id<AuthenticationDelegate>  authenticator

+ (id)sharedInstance;

如果您的客户希望通过他们的方法进行身份验证,那么他们必须向AuthenticationDelegate协议确认并实现其方法.他们必须将authenticator属性设置为其所限定的类.然而它的单身人士.因此,只要对象被实例化,他们就可以设置它.因此他们可以使用他们的身份验证器

但要确保验证者剂量指向零.您可以实现setAuthenticator:方法,以便当客户端将此设置为nil时,authenticator将指向UseRMANager.

static UseRMANager *_sharedInstance = nil;

@implementation UseRMANager

@synthasize authenticator;

+ (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;
}

-(void)init {
    self = [super init];
    if (self) {
        self.authenticator = nil;
    }
}

-(void)setAuthenticator:(id<AuthenticationDelegate>)inAuthenticator {
    if (!inAuthenticator) {
        __authenticator = self;
    } else {
        __authenticator = inAuthenticator;
    }
}

#pragma mark - AuthenticationDelegate

-(void) authenticateUser:(User*)inUser
{
    // Your Authentication Code.
}

希望这可以帮助…

大佬总结

以上是大佬教程为你收集整理的ios – 如何使我的单例类可扩展?全部内容,希望文章能够帮你解决ios – 如何使我的单例类可扩展?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。