objective-c单例类实现

来源:互联网 发布:软件开发编码规范 编辑:程序博客网 时间:2024/05/17 21:58
  1. //Singleton类声明  
  2. #import    <Foundation/Foundation.h>  
  3.   
  4. @interface    Singleton :NSObject  
  5.   
  6. +(Singleton*)GetInstance;  
  7.   
  8. -(void)SayHello;  
  9.   
  10. @end  
  11.   
  12.   
  13.   
  14.   
  15.   
  16. //Singleton类实现  
  17.   
  18. #import    "Singleton.h"  
  19.   
  20. @implementation    Singleton  
  21.   
  22. static    Singleton    *myInstance =nil;  
  23.   
  24. +(Singleton*)GetInstance{  
  25.       
  26.     @synchronized([Singleton    class]){  
  27.           
  28.         if(myInstance ==nil){  
  29.               
  30.             myInstance = [[self    alloc]init];  
  31.               
  32.         }  
  33.           
  34.     }  
  35.       
  36.     return    myInstance;  
  37.       
  38. }  
  39.   
  40. +(id)alloc{  
  41.       
  42.     @synchronized([Singleton    class]){  
  43.           
  44.         if (myInstance ==nil) {  
  45.               
  46.             myInstance = [super    alloc];  
  47.   
  48.             return myInstance;  
  49.               
  50.         }  
  51.     }  
  52.       
  53.     return    nil;  
  54.       
  55. }  
  56.   
  57. -(id)init{  
  58.       
  59.     self = [super    init];  
  60.       
  61.     if(self !=nil){  
  62.           
  63.         NSLog(@"初始化数据");  
  64.           
  65.     }  
  66.       
  67.     return    self;  
  68.       
  69. }  
  70.   
  71. -(void)SayHello{  
  72.       
  73.     NSLog(@"Hello,world!");  
  74.       
  75. }  
  76.   
  77. @end  
  78.   
  79. //================================================  
  80.   
  81. Main方法调用  
  82.   
  83. #import    <Foundation/Foundation.h>  
  84.   
  85. #import    "Singleton.h"  
  86.   
  87. int    main (int    argc,const    char    * argv[])  
  88.   
  89. {  
  90.       
  91.     @autoreleasepool{  
  92.           
  93.         Singleton    *singleton = [Singleton    GetInstance];  
  94.           
  95.         [singleton    SayHello];  
  96.           
  97.         singleton = [Singleton    new];  
  98.           
  99.         [singleton    SayHello];  
  100.           
  101.     }  
  102.       
  103.     return    0;  
  104.       
  105. }  
  106. 原文链接:http://blog.csdn.net/lanergaming/article/details/7597267
原创粉丝点击