IPhone开发学习笔记:单例模式的实现

首先推荐非常棒的文章:http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c/

下面是实现代码:

  
    
static MyGizmoClass * sharedGizmoManager = nil;

+ (MyGizmoClass * )sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init];
// assignment not done here
}
}
return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone * )zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager
= [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone * )zone
{
return self;
}

- (id)retain
{
return self;
}

- (unsigned)retainCount
{
return UINT_MAX; // denotes an object that cannot be released
}

- ( void )release
{
// do nothing
}

- (id)autorelease
{
return self;
}

简单解释下,详细的请看上面的那篇文章。

 

@synchronized(self) : 这个就是同步语义,这里会自动加锁,以保证多线程的环境,不会new出多个实例来。
[[self alloc] 会默认调用 [self allocWithZone] 所以在sharedManager里没有将值给 sharedGizmoManager

你可能感兴趣的:(iPhone开发)