您的位置:首页 > 其它

单例模式1

2015-08-12 08:54 281 查看
// 单例模式:可以保证在程序运行过程中,一个类只有一个示例 (一个对象)<pre name="code" class="objc">/**
*  static

1. 修饰全局变量

全局变量的作用于仅限于当前文件内部

2. 修饰局部变量

局部变量的生命周期 跟 全局变量 类似
不能改变作用域
能够保证局部变量永远只初始化一次,在程序运行过程中永远只有一份内存

*/

int b = 1;

- (void)test {
int a = 1;
a++;
b++;

static int c = 1; // 只初始化一次,
c++;
NSLog(@"a = %d",a);
NSLog(@"b = %d",b);
NSLog(@"c = %d",c);
}


// 懒汉式
static id _musicTool;
/**
*  设置为static的原因
这个全局变量,不设置为static,可以通过extern引用这个全局变量
然后对这个变量进行操作修改,就不会是单例了。
*/

extern id _musicTool;// 引用某个全局变量 并非定义

// 懒加载
- (NSArray *)musics {

if (!_musics) {
_musics = [[NSMutableArray alloc] init];
}
return _musics;
}

// 重写 alloc内部会调用这个方法
+ (id)allocWithZone:(struct _NSZone *)zone {

//#if 0
//    @synchronized(self) {
//        if (_musicTool == nil) {
//            _musicTool = [super allocWithZone:zone];
//        }
//    }
//    return _musicTool;
//#endif
//
return [super allocWithZone:zone];
}

+ (instancetype)sharedMusicTool {

// 防止频繁加锁
if (_musicTool == nil) {

@synchronized(self) {

// 防止创建多次
if (_musicTool == nil) {
_musicTool = [[self alloc] init];
}
}

}
return _musicTool;
}

- (id)copyWithZone:(NSZone *)zone {

return _musicTool;

}
static id _instance;

// load 先执行 然后initialize

//  print result 一目了然
//2015-08-11 14:32:16.027 1.单例模式[7868:331212] load - load1
//2015-08-11 14:32:16.031 1.单例模式[7868:331212] initialize load <SoundTool: 0x7983ca30>
//2015-08-11 14:32:16.031 1.单例模式[7868:331212] load - load2

/**
*  当类只要一被加载到oc运行时环境中,就会调用一次load,而且一个类只会加载一次
*/
+ (void)load { // load只调用一次 ,恶汉式

NSLog(@"load - load1");

_instance = [[self alloc] init];  相当于+ initialize

NSLog(@"load - load2");

}

/**
*  当第一次使用这个类的时候才会调用
*/

+ (void)initialize {

_instance = [[self alloc] init];

NSLog(@"initialize load %@",_instance);

}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {

if (_instance == nil) {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}

+ (instancetype)sharedSoundTool {

return _instance;

}

- (id)copyWithZone:(NSZone *)zone {

return _instance;

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