Swift World: Design Patterns - Singleton

Singleton is very popular in Cocoa. We can find different use cases. The following are two examples.

let default = NotificationCenter.default
let standard = UserDefaults.standard

We will not talk about what singleton is and its advantages. You can find so many resources on the Internet. We want to focus on how to write our own.

Do you remember how to do this in the Objective-C world? Here is a template which maybe you’ve ever seen. The sharedInstance = [[Car alloc] init]; will only executed once. This is guaranteed by dispatch_once.

@interface Car : NSObject
@end

@implementation car

+ (instancetype)sharedInstance {
    static Car *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Car alloc] init];
    });
    return sharedInstance;
}

@end

What about Swift?

class Car {
    static let sharedInstance = Car()
}

or a little complex

class Car {
    static let sharedInstance: Car = {
        let instance = Car()
        return instance
    }()
}

Really? It’s so simple. Then where is dispatch_once? How do you guarantee the codes only run once? The secret is the ‘static’ keywords. The static property will be lazily initialized once and only once.

Thank you for your time.

Please enable JavaScript to view the <a href=”https://disqus.com/?ref_noscript”>comments powered by Disqus.</a>

    原文作者:算法小白
    原文地址: https://juejin.im/entry/58c2331e8ac2470720f44eff
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞