Singleton

Singleton implementation

Objective-C中单例模式的实现

Singleton Design Pattern for Objective-C

1
2
3
4
5
6
7
8
9
+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

Avoid abusing singleton

避免滥用单例

Singleton introduces globla variable, which may lead to coupling of far-away components.

Note the life circle of an object, to see if it confirm to “will always has one instance”. If NO, we can not use Singleton here.