美文网首页
学习笔记 - 两行代码创建单例

学习笔记 - 两行代码创建单例

作者: 听雨花春风 | 来源:发表于2016-07-20 20:08 被阅读28次

利用两行代码创建单例


// 帮助实现单例设计模式

// .h文件的实现
#define SingletonH(methodName) + (instancetype)shared##methodName;

// .m文件的实现
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instance; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instance; \
}

#else // 不是ARC

#define SingletonM(methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return 1; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
    return _instance; \
} \
 \
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
    return _instance; \
}

#endif

相关文章

  • 学习笔记 - 两行代码创建单例

    利用两行代码创建单例

  • iOS - 单例创建

    Swift创建单例 代码如下:Swift5 对应OC创建单例

  • 23种设计模式学习总结

    创建型设计模式 主要解决对象的创建问题,封装复杂的创建过程,解耦对象的创建代码合使用代码。 单例模式 单例模式用来...

  • Swift 中创建单例

    Swift 中使用单行单例法来创建单例,代码如下: 通过分析 stack trace 后发现,执行下面代码时,调用...

  • flutter mobx状态管理

    依赖 创建对象 以计数例子为例,创建一个counter.dart文件,代码如下: 注意:必须包含以下两行代码,才可...

  • Swift中单例的创建方法

    不废话,直接看代码: swift中单例的创建非常简单了,以下从不同的角度来创建单例 方法一: let修饰的常量 -...

  • 单例模式

    单例模式 1. 入门 测试: 结果: 2 . 同步锁单例 这种方式创建单例不好,延迟,因为代码块在任何一个时刻都是...

  • 单例模式

    单例模式 单例模式:用来保证一个对象只能被创建一次。 普通版 代码实现如下 同步锁单例 单例模式如果再多线程中使用...

  • [iOS Swift] Singleton——单例模式的使用与理

    单例模式属于创建型的设计模式。它提供了一种创建对象的最佳方式。 示例代码: 使用方式: 理解 Swift的单行单例...

  • Android 丨 单例模式

    面试过程中,单例模式总是会被问及,所以抽时间总结了一份单例相关的笔记 单例概念 单例模式是一种对象的创建模式,它用...

网友评论

      本文标题:学习笔记 - 两行代码创建单例

      本文链接:https://www.haomeiwen.com/subject/deovjttx.html