iOS设计模式之一:单例模式

来源:互联网 发布:js删除cookie值的方法 编辑:程序博客网 时间:2024/05/29 16:41

单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。


#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

当然iOS5 以上启用ARC就简单多了:

static RootViewController* sharedRootController = nil;
 
+(RootViewController *) sharedController{
    @synchronized(self){
        if (sharedRootController == nil) {
           sharedRootController = [[self alloc] init];
        }
    }
    return  singleController;
}



0 0
原创粉丝点击