Using Singleton Pattern in Objective-C
Singleton 是一個 Class 設計為確保只有單一 instance,然後提供讓整個 application 都可以 access 進來存取。Singleton pattern 有多個設計好處:
程式規劃為:
以下為一個在 Objective-C 裡面設計 Singletons 的範本。
MySingleton.h
MySingleton.m
使用 Singleton 起來可以變得如此容易
以上可以額外參考 Wikipedia 對於 Design patterns: Singleton pattern 了解更多。
- Controlled access to sole instance - 因為 Singleton class 封裝了單一 instance,他可以限制控制 client (呼叫者) 如何和怎麼存取。
- Reduced name space - 對於全域變數而言,Singleton 可以提升強化。將命名部份統一在單一 Instance。
- Permits refinement of operations and representation - 在 Run-time 時候可以透過這 instance 來控制設定 application。

- 建立 Public class
- 建立 private static 的 instance
- 建立 Method 讓外部可以呼叫使用
- 檢查目前 Instance,如果不存在回傳一份新的,如果已經存在回傳已經建立好的。
以下為一個在 Objective-C 裡面設計 Singletons 的範本。
MySingleton.h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface MySingleton : NSObject { | |
} | |
+(MySingleton*)getInstance; | |
-(void) doSomething; | |
@end |
MySingleton.m
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation MySingleton | |
static MySingleton* _sharedInstance = nil; | |
+(MySingleton*)getInstance | |
{ | |
@synchronized([MySingleton class]) | |
{ | |
if (!_sharedInstance) | |
[[self alloc] init]; | |
return _sharedInstance; | |
} | |
return nil; | |
} | |
+(id)alloc | |
{ | |
@synchronized([MySingleton class]) | |
{ | |
NSAssert(_sharedInstance == nil, | |
@"Attempted to allocate a second instance of a singleton."); | |
_sharedInstance = [super alloc]; | |
return _sharedMySingleton; | |
} | |
return nil; | |
} | |
-(id)init { | |
self = [super init]; | |
if (self != nil) { | |
// initialize stuff here | |
} | |
return self; | |
} | |
-(void)doSomething { | |
NSLog(@"Do the thing client want!"); | |
} | |
@end |
使用 Singleton 起來可以變得如此容易
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[[MySingleton getInstance] doSomething]; |
以上可以額外參考 Wikipedia 對於 Design patterns: Singleton pattern 了解更多。
補充了 Pseudo code。
ReplyDelete