iOS開發單例模式 dispatch_once


iOS開發單例模式

什麼是單例

單例模式是一種常用的軟件設計模式。在它的核心結構中只包含一個被稱爲單例類的特殊類。通過單例模式可以保證系統中一個類只有一個實例而且該實例易於外界訪問,從而方便對實例個數的控制並節約系統資源。如果希望在系統中某個類的對象只能存在一個,單例模式是最好的解決方案。

iOS開發中如何使用單例

傳統的單例構造方法

+ (id)sharedInstance

{

    static id sharedInstance;

    if(sharedInstance == nil){

        sharedInstance = [[]selfalloc] init]

    }

    return sharedInstance;

}

多線程下的隱患

在多線程的情況下,如果兩個線程幾乎同時調用sharedInstance()方法會發生什麼呢?有可能會創建出兩個該類的實例。爲了防止這種情況我們通常會加上鎖

+ (id)sharedInstance

{

    static id sharedInstance;

    @synchronized(self)

        if(sharedInstance == nil){

            sharedInstance = [[]selfalloc] init]

        }          

    }

    return sharedInstance;

}

dispatch_once

iOS 4.0 引進了 GCD ,其中的 **dispatchonce**,它即使是在多線程環境中也能安全地工作,非常安全。dispatchonce是用來確保指定的任務將在應用的生命週期期間,僅執行一次。以下是一個典型的源代碼以初始化的東西。它可以優雅通過使用dispatch_once來創建一個單例。

+ (id)sharedInstance

{

    static dispatch_once_t once;

    static id sharedInstance;

    dispatch_once(&once, ^{

        sharedInstance = [[selfalloc] init];

    });

    return sharedInstance;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章