单例模式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; }
相关文章推荐
- hdu 3665 Seaside(最短路)
- 聪明的kk nyoj 171
- Unix套接字地址结构
- Android API Guides –Device Compatibility
- 大约Java有点感悟---开发商根本上感悟学习
- ECLIPSE IDEA 调音 1
- [C语言][LeetCode][27]Remove Element
- 一次MySQL慢查询导致的故障
- HDOJ-1513-Palindrome
- HDU 3853 LOOPS(期望DP)(第一篇期望dp)
- C++ <VS2008> 使用Excel类创建,读取,查询,写入,修改,删除
- 手动实现数组slice方法跟splice方法
- WINCE注册表中IClass值的确定
- hdu 1075 What Are You Talking About (字典树·文字翻译)
- STL之一:map用法详解
- 360在线笔试编程题
- c++ 11 游记 之 decltype constexpr
- javafx drag
- FZU Problem 1853 Number Deletion
- 【Maven】第一次使用maven的配置(win8,eclipse,Intellij IDEA)