自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

解析Cocoa單態(tài) singleton設計模式

移動開發(fā) iOS
本文介紹的是解析Cocoa單態(tài) singleton設計模式,主要是以代碼來實現(xiàn)實例操作,我們先來看內(nèi)容。

解析Cocoa單態(tài) singleton設計模式是本文要介紹的內(nèi)容,不多說,先來看內(nèi)容,如果你準備寫一個類,希望保證只有一個實例存在,同時可以得到這個特定實例提供服務的入口,那么可以使用單態(tài)設計模式。單態(tài)模式在Java、C++中很常用,在Cocoa里,也可以實現(xiàn)。

由于自己設計單態(tài)模式存在一定風險,主要是考慮到可能在多線程情況下會出現(xiàn)的問題,因此蘋果官方建議使用以下方式來實現(xiàn)單態(tài)模式

  1. static MyGizmoClass *sharedGizmoManager = nil;  
  2.    
  3.  (MyGizmoClass*)sharedManager  
  4. {  
  5.     @synchronized(self) {  
  6.         if (sharedGizmoManager == nil) {  
  7.             [[self alloc] init]; // assignment not done here  
  8.         }  
  9.     }  
  10.     return sharedGizmoManager;  
  11. }  
  12.    
  13.  (id)allocWithZone:(NSZone *)zone  
  14. {  
  15.     @synchronized(self) {  
  16.         if (sharedGizmoManager == nil) {  
  17.             sharedGizmoManager = [super allocWithZone:zone];  
  18.             return sharedGizmoManager;  // assignment and return on first allocation  
  19.         }  
  20.     }  
  21.     return nil; //on subsequent allocation attempts return nil  
  22. }  
  23.   (id)copyWithZone:(NSZone *)zone  
  24. {  
  25.     return self;  
  26. }  
  27.    
  28.  (id)retain  
  29. {  
  30.     return self;  
  31. }  
  32.    
  33.  (unsigned)retainCount  
  34. {  
  35.     return UINT_MAX;  //denotes an object that cannot be released  
  36. }  
  37.    
  38.  (void)release  
  39. {  
  40.     //do nothing  
  41. }  
  42.    
  43. (id)autorelease  
  44. {  
  45.     return self; 

小結(jié):解析Cocoa單態(tài) singleton設計模式的內(nèi)容介紹完了,希望本文對你有所幫助!

責任編輯:zhaolei 來源: Cocoa China
相關推薦

2012-08-22 10:10:25

單態(tài)單態(tài)設計設計模式

2023-07-31 12:27:30

單例設計模式

2011-07-26 15:29:36

Cocoa 模式

2009-09-02 16:23:27

C# Singleto

2009-07-09 17:30:59

Singleton模式C++ SingletJava Single

2021-02-01 10:01:58

設計模式 Java單例模式

2011-07-07 16:14:37

Cocoa MVC 模型

2021-03-02 08:50:31

設計單例模式

2013-11-26 16:20:26

Android設計模式

2016-03-28 10:23:11

Android設計單例

2009-08-31 16:12:02

C#使用Singlet

2022-06-07 08:55:04

Golang單例模式語言

2022-02-06 22:30:36

前端設計模式

2009-07-08 17:25:05

Java Single

2009-08-25 18:04:30

C#實現(xiàn)Singlet

2009-08-31 15:48:02

C# Singleto

2024-02-04 12:04:17

2021-09-16 06:44:05

組合模式設計

2015-09-06 11:07:52

C++設計模式單例模式

2009-12-15 13:26:33

Ruby單態(tài)方法
點贊
收藏

51CTO技術(shù)棧公眾號