微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Cocoa的单态(singleton)设计模式

如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。单态模式在Java、C++中很常用,在Cocoa里,也可以实现。

由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:

 

  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.  
  24. - ( id ) copyWithZone : ( NSZone * ) zone
  25. {
  26.     return self;
  27. }
  28.  
  29. - ( id ) retain
  30. {
  31.     return self;
  32. }
  33.  
  34. - ( unsigned ) retainCount
  35. {
  36.     return UINT_MAX;   //denotes an object that cannot be released
  37. }
  38.  
  39. - ( void ) release
  40. {
  41.     //do nothing
  42. }
  43.  
  44. - ( id ) autorelease
  45. {
  46.    return self;
  47. }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐