Swift-Swift的Singleton三种写法

 

第一种:

import Foundation

class SingletonA : NSObject {
    
    static let sharedInstance: SingletonA = SingletonA()
    
    private init() {
        print("AAA");
    }
    
}

 

第二种:

import Foundation

class SingletonB {
    
    class var sharedInstance: SingletonB {
        struct Static {
            static let instance: SingletonB = SingletonB()
        }
        return Static.instance
    }
    
    private init() {
        print("BBB");
    }
    
}

 

第三种:

import Foundation

class SingletonC {
    
    class var sharedInstance: SingletonC {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SingletonC? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SingletonC()
        }
        return Static.instance!
    }
    
    private init() {
        print("CCC");
    }
    
}

 

posted @ 2016-03-28 15:26  我大沈阳无敌  阅读(303)  评论(0编辑  收藏  举报