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
时间: 2024-10-14 18:06:21