iOS設計模式之單例模式

來源:互聯網
上載者:User

標籤:ios設計模式之單例模式   ios   設計模式   設計   

單例模式:總是返回自己的同一個執行個體,它提供了對類的對象所提供的資源的全域訪問點,並且返回的執行個體只能被執行個體化一次.

單例設計模式設計需要考慮的兩個問題:

(1) :發起調用的對象不能以其他分配方式執行個體化單例對象,否則,就有可能建立單例類的多個執行個體

(2) :對單例對象執行個體化的限制應該與引用計數記憶體模型共存.


Singleton.h

#import <Foundation/Foundation.h>


@interface Singleton :NSObject


+(Singleton *) sharedInstance;


@end


Singleton.m

#import "Singleton.h"


@implementation Singleton


staticSingleton *sharedSingleton = nil;


+(Singleton *) sharedInstance{

    

    if (sharedSingleton ==nil) {

        //sharedSingleton = [[Singleton alloc] init];

        //     --------->>>>>(1)

        //sharedSingleton = [[super allocWithZone:NULL] init];

       /*

            這裡使用 super而不適用self的原因是self已經重載了allocWithZone方法

            所以通過調用父類的方法,實現記憶體的分配

            其實allocWithZone方法內部調用的是NSAllocateObject方法

        */

        //     --------->>>>>(2)

        sharedSingleton = [NSAllocateObject([selfclass], 0,NULL) init];

       /*

            第一個參數是 類的類型

            第二個參數是用於索引的執行個體變數的額外位元組數,總是 0

            第三個參數是用於指定記憶體中分配的地區,一般為NULL,表示為預設區域

            這裡不適用(1)而使用(2)的原因是處理不管是執行個體化Singleton還是子類,都適用

         */

    }

    returnsharedSingleton;

}



/*

    調用類的allocWithZone傳入NSZone參數,為即將產生的新對象分配空間

    重載的目的是當使用對象的alloc方法時不會產生新的執行個體

    因為 alloc方法其實調用的就是 allocWithZone:NULL方法,防止因 alloc而產生其他的執行個體

 

 */

+(id) allocWithZone:(struct_NSZone *)zone{


    return [[selfsharedInstance] retain];

}



/*

    這裡重載copyWithZone的目的,是防止使用 copy方法時產生其他的執行個體

 */

-(id) copyWithZone:(NSZone *)zone{

    

    return self;


}


-(id) retain{

    

    return self;

}


-(NSUInteger) retainCount{

    

    returnNSUIntegerMax;

}


-(void) release{

    

    //什麼也不做


}


-(id) autorelease{

    

    return self;

}


@end



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

iOS設計模式之單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.