2012年11月24日 星期六

Singleton Pattern

SingletonObject.h
#import <Foundation/Foundation.h>
@interface SingletonObject : NSObject {
@private
int count;
}

//統一透過此函式來使用 Singleton 物件的方法
+ (SingletonObject *)sharedSingletonObject;
//增加
- (void)addCount;
//呈現
- (void)showCount;
@end


  1. #import "SingletonObject.h"
  2.  
  3. @implementation SingletonObject
  4.  
  5. //宣告一個靜態的Singleton物件
  6. static SingletonObject *_singletonObject = nil;
  7.  
  8. - (id)init {
  9. self = [super init];
  10. if (self) {
  11.  
  12. //將 count 初始化為0
  13. count = 0;
  14. }
  15.  
  16. return self;
  17. }
  18.  
  19. //執行時會判斷是否 _singletonObject 已經完成記憶體配置
  20. + (SingletonObject *)sharedSingletonObject {
  21.  
  22. @synchronized([SingletonObject class]) {
  23.  
  24. //判斷_singletonObject是否完成記憶體配置
  25. if (!_singletonObject)
  26. [[self alloc] init];
  27.  
  28. return _singletonObject;
  29. }
  30.  
  31. return nil;
  32. }
  33.  
  34. + (id)alloc {
  35. @synchronized([SingletonObject class]) {
  36.  
  37. //避免 [SingletonObject alloc] 方法被濫用
  38. NSAssert(_singletonObject == nil, @"_singletonObject 已經做過記憶體配置");
  39. _singletonObject = [super alloc];
  40.  
  41. return _singletonObject;
  42. }
  43.  
  44. return nil;
  45. }
  46.  
  47. - (void)addCount {
  48. count += 1;
  49. }
  50.  
  51. - (void)showCount {
  52. NSLog(@"%d", count);
  53. }
  54.  
  55. - (void)dealloc {
  56. [super dealloc];
  57. }
  58.  
  59. @end

沒有留言:

張貼留言