您的位置:首页 > 移动开发 > Objective-C

Objective-C编程之道iOS设计模式单例解析(1)

2013-07-17 20:01 387 查看
此书中第85页有如下一段话:

The alloc call is forwarded to super, which means NSObject will take care of the object allocation. If we subclass Singleton without any modification, the returned instance is always Singleton. Because Singleton overrides all
the instantiation-related methods, it is quite tricky to subclass it.

起初我不了解一个问题,我的测试以下两个方法创建子类实例,结果均运行良好。比如SingletonSon:Singleton,子类不做任何修改,当调用[SingletonSon sharedInstance]或[SingletonSon alloc]时返回的实例是SingletonSon而不是Singleton。这与原文说法相反,原文说,如果不做修改的子类化Singleton,返回的实例总是Singleton。

+(Singleton *) sharedInstance
{
if(sharedSingleton==nil)
{
sharedSingleton=[[super allocWithZone:NULL] init];
}
return sharedSingleton;
}


+(Singleton *) sharedInstance
{
if(sharedSingleton==nil)
{
sharedSingleton=[NSAllocateObject([self class],0,NULL) init];
}
return sharedSingleton;
}


这里我忽略一个问题,即我们在Singleton.m文件定义了一个static Singleton* sharedSingleton类变量。这个变量只有一份,父类与其子类共享,初始值为nil,所以如果先调用[Singleton sharedInstance],使sharedSingleton指向了Singleton类的实例对象,那么之后调用[SingletonSon sharedInstance]或[SingletonSon alloc],返回值将总是sharedSingleton所指向的Singleton类的实例对象。[SingletonSon
alloc]也无法创建SingletonSon对象,它不会调用NSObject的alloc方法而是调用Singleton的alloc方法,因为其父类Singleton重写实例化相关的方法,而此方法将直接返回sharedSingleton所指向的值。

+(id) allocWithZone:(NSZone *)zone //Singleton重写了实例化相关方法
{
return [[self sharedInstance] retain];
}


所以要子类化Singleton,并希望处理好子类和父类的实例化问题,需要采用第二种方式。

@implementation SingletonSon
static Singleton *shareSingleton=nil; //向上转型,重定义自己的sharedsingleton类变量,不与父类共享。
+(SingletonSon *) shareInstance
{
if(sharedSingleton==nil)
{
//不调用父类alloc方法,在此调用父类alloc方法可能回调此方法,从而产生死循环,我们直接创建对象。
sharedSingleton=[NSAllocateObject(self class),0,NULL) init];
}
}// 子类可以重写一下retain copy release autorelease进行合适的内存管理。
@end


我是小强,请多多指教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: