單例模式,顧名思義就是只有一個實例,由它自行實例化並向整個系統提供這唯一的實例。
首先在 .h 文件中宣告:
#import <Foundation/Foundation.h> @interface SingletonClass : NSObject + (id)sharedInstance; @end
然後在 .m 文件中實現:
#import "SingletonClass.h"
@implementation SingletonClass
static SingletonClass *getInstance;
+ (id)sharedInstance {
@synchronized([SingletonClass class]) {
if (getInstance == nil) {
getInstance = [[SingletonClass alloc] init];
}
}
return getInstance;
}
@end
[[SingletonClass sharedInstance] xxx];
銷毀也就是對單例的釋放,通常在應用終止時進行,可以在 delegate 方法中實現:
- (void)applicationWillTerminate:(UIApplication *)application {
[SingletonClass destroyDealloc];
}
銷毀方法如下:
+ (void)destroyDealloc {
if ([getInstance retainCount] != 1)
return;
[getInstance release];
getInstance = nil;
}
單例模式的好處:
缺點:單例模式會讓物件變成全域的,降低了每個獨立模組的靈活性。