// 地球只有一个,所以声明一个地球对象就可以了,千万不能声明两个啊!同理,有时候一个类也有只能有一个对象的情况,例如服务器,只想存到一个里 // 面,这样子,下次才可以取出上次存的数据。
//用全局变量来实现单例模式
//在此定义一个全局变量 地球,然后在单例方法中一直返回这个全局变量,那也可以实现单例模式
Earth * global=nil;
//在单例方法中一直返回这个全局变量,但第一次调用时要创建这个对象
+(Earth *)defaultEarth
{
if (global==nil) {
global = [[ Earth alloc]init];
}
return global;
}
****************************************
//用静态局部变量实现单例模式
+(Earth *)defaultEarth
{
static Earth* obj=nil;
if (obj==nil) {
obj=[[Earth alloc]init];
}
return obj;
}
**************************************
用GCD实现单例,超简单
- (Earth *)shareEarth
{
static Earth *sharedEarthInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedEarthInstance = [[self alloc] init];
});
return sharedEarthInstance;
}
原文:http://www.cnblogs.com/hyuganatsu/p/Singleton.html