IOS学习之 -- 单例模式正确写法

#import "Singleton.h"

@implementation Singleton
static Singleton* _instance = nil;
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
    _instance = [[super allocWithZone:NULL] init] ;
}) ;
return _instance ;
}

+(id) allocWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}

-(id) copyWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}
@end

然后测试:

Singleton* obj1 = [Singleton shareInstance] ;
NSLog(@"obj1 = %@.", obj1) ;
     
Singleton* obj2 = [Singleton shareInstance] ;
NSLog(@"obj2 = %@.", obj2) ;
     
Singleton* obj3 = [[Singleton alloc] init] ;
NSLog(@"obj3 = %@.", obj3) ;
     
Singleton* obj4 = [[Singleton alloc] init] ;
NSLog(@"obj4 = %@.", [obj4 copy]) ;

结果:

2014-12-15 16:11:24.734 ObjcSingleton[8979:303] obj1 = 
2014-12-15 16:11:24.735 ObjcSingleton[8979:303] obj2 = 
2014-12-15 16:11:24.736 ObjcSingleton[8979:303] obj3 = 
2014-12-15 16:11:24.736 ObjcSingleton[8979:303] obj4 = 

你可能感兴趣的:(IOS学习之 -- 单例模式正确写法)