创建单例的两种方式(懒汉式&GCD)
来源:互联网 发布:分享文章赚钱系统源码 编辑:程序博客网 时间:2024/06/03 05:06
懒汉式:
// 创建静态全局变量static id instance;// 重写allocWithZone方法+(instancetype)allocWithZone:(struct _NSZone *)zone{ if (instance == nil) { // 如果对象为空,那么再加锁(防止频繁加锁) @synchronized(self) { if (instance == nil) { // 防止创建多次 instance = [super allocWithZone:zone]; } } } return instance;}// 封装一个初始化方法方便初始化对象的时候使用+(instancetype)sharedLanHan{ if (instance == nil) { @synchronized(self) { if (instance == nil) { instance = [[super alloc] init]; } } } return instance;}-(id)copyWithZone:(NSZone *)zone{ // 防止copy时候产生新对象 return instance;}
GCD:
// 创建静态全局变量static id _instance;+(instancetype)allocWithZone:(struct _NSZone *)zone{ // GCD确保代码只执行一次,并且有线程保护 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance;}+(id)sharedGCD{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[super alloc] init]; }); return _instance;}-(id)copyWithZone:(NSZone *)zone{ return _instance;}
0 0
- 创建单例的两种方式(懒汉式&GCD)
- 两种创建单例模式的方式-懒汉式与饿汉式
- 单例模式的两种方式:懒汉式、饿汉式
- 单例模式的两种方式《饿汉式》和《懒汉式》 面试经常被考到
- ios-单例模式饿汉式&GCD&懒汉式&宏方式的实现和条件编译
- GCD常用基本API介绍以及创建单例的两种方式
- 创建单例Singleton的三种方式:懒汉式、饿汉式、枚举类
- GCD单例-懒汉式&饿汉式
- 创建单例的两种方式
- 单例的两种创建方式
- 单例的两种创建方式
- 单例模式的两种方式:饿汉模式与懒汉模式
- 单例模式的两种形式(恶汉式,懒汉式)
- 单例模式——懒汉式和饿汉式的创建方式
- GCD方式创建单例
- GCD方式创建单例
- 单例模式两种模式--饿汉式和懒汉式
- 懒汉式的安全优化方式,两种方式。线程同时运行的时候,不会创建两个对象
- 高性能网站架构设计之缓存篇(1)- Redis的安装与使用
- leetcode 每日一题 34. Search for a Range
- Java之泛型进阶——泛型代码转化为普通代码
- 判断任意数据是否奇偶数
- java 线程2
- 创建单例的两种方式(懒汉式&GCD)
- Fragment切换
- c++上机报告1-1
- ORACLE优化方案
- 通过 git bash 配置和使用 github
- Windows下安装部署solr 5.5
- 几种编码格式
- leetcode:Add Two Numbers 【Java】
- uva10245 - - The Closest Pair Problem(最近点问题)