Singleton pattern in objc, how to keep init private?

后端 未结 4 1210
说谎
说谎 2020-12-19 23:47

How can i make sure user do not call init, instead client should call sharedSingleton to get a shared instance.

@synthesize delegate;

- (id)init
{
    self          


        
4条回答
  •  无人及你
    2020-12-19 23:54

    I've seen it done two ways.

    1. Throw an exception inside init.
    2. Have the object returned by init be your singleton object.

    Just to be clear, though, don't do this. It's unnecessary and will make your singletons overly difficult to test and subclass.

    edit to add examples

    Throw an exception in init

    - (instancetype)init {
        [self doesNotRecognizeSelector:_cmd];
        return nil;
    }
    
    - (instancetype)initPrivate {
        self = [super init];
        if (self) {
        }
        return self;
    }
    
    + (instancetype)sharedInstance {
        static MySingleton *sharedInstance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[self alloc] initPrivate];
        });
        return sharedInstance;
    }
    

    Have init return your singleton

    - (instancetype)init {
        return [[self class] sharedInstance];
    }
    
    - (instancetype)initPrivate {
        self = [super init];
        if (self) {
        }
        return self;
    }
    
    + (instancetype)sharedInstance {
        static MySingleton2 *sharedInstance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[self alloc] initPrivate];
        });
        return sharedInstance;
    }
    

提交回复
热议问题