Swift之單例模式

三種Swift實現單例模式的方法:全局變量,內部變量,dispatch_once方式spa

1. 全局變量blog

private let _singleton = Singleton()  

class Singleton: NSObject {  
    class var sharedInstance: Singleton {  
        get {  
            return _singleton  
        }  
    }  
}  

  

2. 內部變量get

class Singleton {  
    class var sharedInstance: Singleton {  
        get {  
            struct SingletonStruct {  
                static let singleton: Singleton = Singleton()  
            }  
             return SingletonStruct.singleton  
        }  
    }  
}  

  

3. dispatch_once方式class

class Singleton {  
    class var sharedInstance: Singleton {  
        get {  
            struct SingletonStruct {  
                static var onceToken:dispatch_once_t = 0  
                static var singleton: Singleton? = nil  
            }  
            dispatch_once(&SingletonStruct.onceToken, { () -> Void in  
                SingletonStruct.singleton = Singleton()  
            })  
            return SingletonStruct.singleton!  
        }  
    }  
}
相關文章
相關標籤/搜索