單例模式的意思就是只有一個實例。單例模式確保某一個類只有一個實例,而且自行實例化并向整個系統(tǒng)提供這個實例。這個類稱為單例類。
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+(Singleton *) instance; @end
@implementation Singleton +(Singleton *) instance
{
static Singleton *sharedSingleton_ = nil;
@synchronized(self){
if(sharedSingleton_ == nil){
sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init];
}
}
return sharedSingleton_;
}
+ (id) allocWithZone:(NSZone *)zone
{
return [[self sharedInstance] retain];
}
- (id) copyWithZone:(NSZone*)zone
{
return self;
}
- (id) retain
{
return self;
}
- (NSUInteger) retainCount
{
return NSUIntegerMax;
}
-(void)release
{
[super release];
}
- (id) autorelease
{
return self;
}
@end
當(dāng)然,ios 5以上啟用ARC就簡單多了:
static RootViewController* sharedRootController = nil;
+(RootViewController *) sharedController{
@synchronized(self){
if (sharedRootController == nil) {
sharedRootController = [[self alloc] init];
}
}
return singleController;
}
歡迎轉(zhuǎn)載,但請保留鏈接 http://www.cnblogs.com/limlee
--- GeekLion
|