单例模式

来源:互联网 发布:java同步锁和互斥锁 编辑:程序博客网 时间:2024/05/23 12:02
单例模式 
Java代码  收藏代码
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface TCUtil : NSObject {  
  4.       
  5.     BOOL isOpenedOfPanel_;  
  6. }  
  7.   
  8. @property (nonatomic, assign) BOOL isOpenedOfPanel;  
  9.   
  10. // Singleton stuff  
  11. + (TCUtil *)sharedUtilInstance;  
  12.   
  13. @end  

Java代码  收藏代码
  1. //  
  2. //  TCUtil.m  
  3. //  TrendsCity  
  4. //  
  5. //  Copyright 2011 卓文华讯. All rights reserved.  
  6. //  
  7.   
  8. #import "TCUtil.h"  
  9. #import <QuartzCore/QuartzCore.h>  
  10.   
  11. @implementation TCUtil  
  12.   
  13. @synthesize isOpenedOfPanel = isOpenedOfPanel_;  
  14.   
  15. #pragma mark -  
  16. #pragma mark Singleton stuff  
  17.   
  18. static TCUtil *utilInstance_ = nil;  
  19.   
  20. + (TCUtil *)sharedUtilInstance {  
  21.       
  22.     if (!utilInstance_) {  
  23.           
  24.         utilInstance_ = [[self alloc] init];  
  25.     }  
  26.       
  27.     return utilInstance_;  
  28. }  
  29.   
  30. + (id)alloc {  
  31.       
  32.     NSAssert(utilInstance_ == nil, @"Attempted to allocate a second instance of a singleton.");  
  33.     return [super alloc];  
  34. }  
  35.   
  36. - (id)init {  
  37.       
  38.     self = [super init];  
  39.       
  40.     if (self) {  
  41.           
  42.         isOpenedOfPanel_ = NO;  
  43.     }  
  44.       
  45.     return  self;  
  46. }  
  47.   
  48. #pragma mark -  
  49. #pragma mark Memory management methods  
  50.   
  51. - (void)dealloc {  
  52.       
  53.     [utilInstance_ release];  
  54.     utilInstance_ = nil;  
  55.       
  56.     [super dealloc];  
  57. }  
  58.   
  59. @end  
原创粉丝点击