iOS 設計模式之單例

來源:互聯網
上載者:User

標籤:style   使用   資料   os   類   line   

 

      單例無非就是只有一個執行個體,它確保一個類只有一個執行個體,並且自行執行個體化並向整個系統提供這個執行個體。它經常用來做應用程式層級的共用資源控制。這個模式使用頻率非常高,通過一個單例類,可以實現在不同視窗之間傳遞資料。

     單例模式是所有模式中最簡單的一種設計模式,這一模式的意圖是使得一個對象成為系統中的唯一執行個體。

     說到單例模式,先說下他的優缺點吧:優點就是可以讓程式其他的類去用它,簡單,可以實現不歐諾個視窗之間的資料傳遞;當然有優點,肯定有缺點,缺點就是,在單例中不釋放記憶體,所以一般一個程式最多隻能有4個單例,再多的話,會導致系統奔潰。

     

想要在一個oc中實現一個單例類,必須實現4個步驟

(1):為單例對象,實現一個靜態執行個體,並且初始化,設為nil,一定是加號,類方法;

(2):實現一個執行個體構造方法檢查上面聲明的靜態執行個體是否為nil,如果是則建立並返回一個本類的執行個體

(3):重寫initWithZone方法,用來保證其他人直接使用alloc和init試圖獲得一個新執行個體的時候不產生一個新執行個體,

(4):適當實現allocWitheZone,copyWithZone,release和autorelease

 

 例子:為RootViewController建立一個單例函數:

static RootViewController *shareRootViewController = nil;
+(RootViewController *)sharedController{
        @synchronized(self){
                if(shareRootViewController == nil){
                        shareRootViewController = [[[self alloc] init] autorelease];
                }
        }
        return shareRootViewController;
}

+(id)allocWithZone:(NSZone *)zone{
        @synchronized(self){
                if (shareRootViewController == nil) {
                   shareRootViewController = [super allocWithZone:zone];
                    return  shareRootViewController;
                }
            }
        return nil;
}

 

如果單例對象實由多個線程訪問,那麼就要保證他的安全執行緒。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.