如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。单态模式在Java、C++中很常用,在Cocoa里,也可以实现。
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:
-
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;
-
}有关NSObject协议实现部分还有些不明白,需要查资料多理解。