ios单态(singleton)设计模式
2012-05-27 09:44
441 查看
如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。单态模式在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;
}
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:
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;
}
相关文章推荐
- ios单态(singleton)设计模式
- ios设计模式读书笔记----Singleton(单例)
- [置顶] IOS设计模式之单例模式(Singleton)
- iOS设计模式之 Singleton(单例模式)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- java设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 使用设计模式中的Singleton单例模式来开发iOS应用程序
- iOS 设计模式系列:Singleton – 单例模式
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- iOS 设计模式系列:Singleton – 单例模式
- [IOS 下重温设计模式] - Singleton
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态/单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)