Cocoa的单态(singleton)设计模式

来源:互联网 发布:ios能用java开发吗 编辑:程序博客网 时间:2024/05/19 13:19

http://www.cocoachina.com/b/?p=256

如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。单态模式在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. }

原创粉丝点击