[Swift基础语法入门]代码讲解何为单例

Method 1

class DemoClass{
    //1
    class var sharedInstance:DemoClass{
        //2
        struct Static {
            static var onceToken:dispatch_once_t = 0
            static var instance:DemoClass? = nil
        }
        //3
        dispatch_once(&Static.onceToken){
            // 4
            Static.instance = DemoClass()
        }
        return Static.instance!
    }
}

Method 2

// 方法二
class DemoClass2{
    //1
    class var sharedInstance:DemoClass2{
        //2
        struct Static {
            static let instance = DemoClass2()
        }
        //3
        return Static.instance
    }
}

Method 3

// 方法三
class DemoClass3{
    class var sharedInstance:DemoClass3{
        return sharedInstance3
    }
}
private let sharedInstance3 = DemoClass3()

Method 4

class DemoClass4{
    static let sharedInstance = DemoClass4()
}

参考

THE RIGHT WAY TO WRITE A SINGLETON
Swift Singleton Design Pattern

你可能感兴趣的:([Swift基础语法入门]代码讲解何为单例)