Using Singleton Pattern in Objective-C

Singleton 是一個 Class 設計為確保只有單一 instance,然後提供讓整個 application 都可以 access 進來存取。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

#import <Foundation/Foundation.h>
@interface MySingleton : NSObject {
}
+(MySingleton*)getInstance;
-(void) doSomething;
@end
view raw gistfile1.m hosted with ❤ by GitHub

MySingleton.m

@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
view raw gistfile1.m hosted with ❤ by GitHub

使用 Singleton 起來可以變得如此容易

[[MySingleton getInstance] doSomething];
view raw gistfile1.m hosted with ❤ by GitHub

以上
可以額外參考 Wikipedia 對於 Design patterns: Singleton pattern 了解更多

Comments

Post a Comment