Swift之單例模式

來源:互聯網
上載者:User

標籤:

三種Swift實現單例模式的方法:全域變數,內部變數,dispatch_once方式

1. 全域變數

private let _singleton = Singleton()  class Singleton: NSObject {      class var sharedInstance: Singleton {          get {              return _singleton          }      }  }  

  

2. 內部變數

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

  

3. dispatch_once方式

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!          }      }  }

  

Swift之單例模式

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.