码迷,mamicode.com
首页 > 其他好文 > 详细

THE RIGHT WAY TO WRITE A SINGLETON

时间:2015-10-15 17:47:31      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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

THE RIGHT WAY TO WRITE A SINGLETON

标签:

原文地址:http://www.cnblogs.com/newBlash/p/4882650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!