THE RIGHT WAY TO WRITE A SINGLETON

A TRIP DOWN MEMORY LANE

@interface Kraken : NSObject
@end

@implementation Kraken

+ (instancetype)sharedInstance {
    static Kraken *sharedInstance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        sharedInstance = [[Kraken alloc] init];
    });
    return sharedInstance;
}

@end

 

THE UGLIEST WAY (A.K.A. THE "WHY ARE YOU STILL CODING IN SWIFT IF YOU'RE JUST GOING TO DO THIS" WAY)

class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: TheOneAndOnlyKraken? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = TheOneAndOnlyKraken()
        }
        return Static.instance!
    }
}

 

THE STRUCT WAY (A.K.A. THE "OLD BUT STRANGELY STILL POPULAR" WAY) 

class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        struct Static {
            static let instance = TheOneAndOnlyKraken()
        }
        return Static.instance
    }
}

 

THE GLOBAL VARIABLE WAY (A.K.A. THE "ONE LINE SINGLETON")

private let sharedKraken = TheOneAndOnlyKraken()
class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        return sharedKraken
    }
}

 

THE RIGHT WAY A.K.A. "THE ONE LINE SINGLETON (NOW WITH PROOF!") 

class TheOneAndOnlyKraken {
    static let sharedInstance = TheOneAndOnlyKraken()
}

 

DON'T FORGET THE PRIVATE INIT!

class TheOneAndOnlyKraken {
    static let sharedInstance = TheOneAndOnlyKraken()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}

 

FROM: http://krakendev.io/blog/the-right-way-to-write-a-singleton

posted @ 2015-10-15 15:55  不会骑扫把的胖女巫  阅读(282)  评论(0编辑  收藏  举报