ios設計模式——單例模式

來源:互聯網
上載者:User

標籤:

一、定義

  • 單例模式:保證一個類僅有一個執行個體,並提供一個訪問它的全域訪問點。

  如何保證只能建立一個執行個體

二、使用

  1. 類只能有一個執行個體,而且必須從一個為人熟知的訪問點對其進行訪問
  2. 這個唯一的執行個體只能通過子類化進行擴充,而且擴充的對象不會破壞用戶端代碼

三、代碼

  • 方法一
     1 #import "Singleton.h" 2  3 @implementation Singleton 4  5 static Singleton * shared = nil; 6  7 + (Singleton *)sharedInstance 8 { 9     static dispatch_once_t once;10     dispatch_once(&once, ^{11             shared = [[super allocWithZone:NULL] init];12     });13     14     return shared;15 }16 17 + (instancetype)allocWithZone:(struct _NSZone *)zone18 {19     return [self sharedInstance];20 }21 22 @end

     

  調用:

 1        Singleton * single = [[Singleton alloc] init]; 2         NSLog(@"%@", single); 3          4         Singleton * sing = [Singleton sharedInstance]; 5         NSLog(@"%@", sing); 6          7         Singleton * single1 = [[Singleton alloc] init]; 8         NSLog(@"%@", single1); 9         10         Singleton * sing1 = [Singleton sharedInstance];11         NSLog(@"%@", sing1);

輸出結果:

這樣,當我們調用alloc的時候,會自動調用+ (instancetype)allocWithZone:(struct _NSZone *)zone方法,調用這個方法的時候,就會調用sharedInstance方法,所以這樣不管什麼時候使用這個類,最終都是由sharedInstance返回的,而且,sharedInstance方法,只初始化該對象一次,所以返回的地址都是一樣的。

  • 方法二
 1 #import "Singleton.h" 2  3 @implementation Singleton 4  5 static Singleton * shared = nil; 6  7 + (Singleton *)sharedInstance 8 { 9     if(shared == nil){10         shared = [[self alloc] init];11     }12     return shared;13 }14 15 + (instancetype)allocWithZone:(struct _NSZone *)zone16 {17     static dispatch_once_t once;18     dispatch_once(&once, ^{19         shared = [[super allocWithZone:zone] init];20     });21     22     return shared;23 }24 25 @end

方法一和方法二,執行的效果是一樣的,只是函數的執行數序是不同的,方法一不管調用哪個方法,最後調用的一個是sharedInstance,而方法二,不管調用哪一個函數,最終調用的是allocWithZone。其實底層實現都是一樣的,最終都由[[super allocWithZone:zone] init]返回一個地址給static對象。

 

  

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.