swift語言實現單例模式

來源:互聯網
上載者:User

標籤:單例類   行儲存   targe   key   執行個體   href   輸出   singleton   靜態方法   


Swift實現單例模式

單例模式在各個語言中都有實現,swift語言推出已經幾天了。通過這幾天的看文檔。特奉上寫的Swift的單例實現,供大家學習交流,歡迎指正。


---若轉載請註明出處,本人Github部落格新地址- YueRuo‘s Blog - http://yueruo.github.io ---


因為Swift語言弱化了struct和class之間的界限,這裡我分別給出自己寫的兩種的單例實現

class版本號碼:
class SwiftSingleton{    class func shareInstance()->SwiftSingleton{        struct YRSingleton{            static var predicate:dispatch_once_t = 0            static var instance:SwiftSingleton?

= nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=SwiftSingleton() } ) return YRSingleton.instance! }}

對於單例類。須要一個唯一的對外輸出執行個體的shareInstance方法。而通過官方文檔的查閱,發現對於class來說。靜態方法能夠用class func 來標示。靜態變數使用class var來處理,但這裡我藉助了內部struct的靜態變數來對唯一的instance進行儲存。

調用時,能夠使用

var swiftInstance1=SwiftSingleton.shareInstance()var swiftInstance2=SwiftSingleton.shareInstance()if swiftInstance1===swiftInstance2{//“===”判別是否是同一個執行個體對象    println("they are the same instance!")}

另外,上面使用到了dispatch_once,有過GCD編程經驗的應該會很熟悉,能夠保證安全執行緒,以及僅僅會被調用一次。



struct版本號碼

struct版本號碼與class版本號碼差點兒一致,唯一差別在於對於func使用的keyword由class func變為 static func

struct StructSingleton{    static func shareInstance()->StructSingleton{        struct YRSingleton{            static var predicate:dispatch_once_t = 0            static var instance:StructSingleton?

= nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=StructSingleton() } ) return YRSingleton.instance! }}

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.