iOS設計模式之單例模式

來源:互聯網
上載者:User

標籤:使用   os   io   ar   art   問題   cti   div   

單例模式是iOS常用設計模式中的一種。單例設計模式的作用是使得這個類的一個對象成為系統中的唯一執行個體,因此需要用一種唯一的方法去建立這個對象並返回這個對象的地址。那麼,我們何時使用單例模式呢?1、類只能有一個執行個體,而且必須從一個為人熟知的訪問點對其訪問。2、這個唯一的執行個體只能通過子類化進行擴充,而且擴充的對象不會破壞用戶端代碼。

那麼用Objective-C如何?單例模式呢?下面我們來建立一個Singleton類,在Singleton.h中實現如下

 

  1. @interface Singleton : NSObject  
  2.   
  3. + (Singleton *) sharedInstance;  
  4.   
  5. @end  

 

 

在Singleton.m

  1. @implementation Singleton  
  2.   
  3. static Singleton * sharedSingleton = nil;  
  4.   
  5. + (Singleton *) sharedInstance  
  6. {  
  7.     if (sharedSingleton == nil) {  
  8.         sharedSingleton = [[Singleton alloc] init];  
  9.     }  
  10.     return sharedSingleton;  
  11. }  
  12.   
  13. @end  


這樣就建立一個簡單的單例模式,實際上有一部分程式員也是這樣實現的,但實際上這是一個不“嚴格”版本,在實際中使用,可能會遇到發起調用的對象不能以其他分配方式執行個體化單例對象,否則,就會建立多個執行個體。(之前有人和我討論過這個問題,說使用者應該嚴格按照介面來使用,當實際上Singleton是一個對象,我們不能保證使用者不會使用其他的方法去建立(比如alloc),這個時候他就會建立多個執行個體,這樣就會出現這些無法感知的bug)

 

 

下面我對Singleton.m的進行改進

  1. @implementation Singleton  
  2.   
  3. static Singleton * sharedSingleton = nil;  
  4.   
  5. + (Singleton *) sharedInstance  
  6. {  
  7.     if (sharedSingleton == nil) {  
  8.         sharedSingleton = [[super allocWithZone:NULL] init];  
  9.     }  
  10.     return sharedSingleton;  
  11. }  
  12.   
  13. + (id) allocWithZone:(struct _NSZone *)zone  
  14. {  
  15.     return [[self sharedInstance] retain];  
  16. }  
  17.   
  18. - (id) copyWithZone:(NSZone *) zone  
  19. {  
  20.     return self;  
  21. }  
  22.   
  23. - (id) retain  
  24. {  
  25.     return self;  
  26. }  
  27.   
  28. - (NSUInteger) retainCount  
  29. {  
  30.     return NSUIntegerMax;  
  31. }  
  32.   
  33.   
  34. - (void) release  
  35. {  
  36.     //  
  37. }  
  38.   
  39. - (id) autorelease  
  40. {  
  41.     return self;  
  42. }  
  43.   
  44. @end  


也許你注意到了,我重載了allocWithZone:,保持了從sharedInstance方法返回的單例對象,使用者哪怕使用alloc時也會返回唯一的執行個體(alloc方法中會先調用allocWithZone:建立對象)。而retain等記憶體管理的函數也被重載了,這樣做讓我們有了把Singleton類變得“嚴格”了。

聯繫我們

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