美文网首页
单例的实现

单例的实现

作者: March_Cullen | 来源:发表于2017-03-02 21:31 被阅读0次

一、使用GCD实现

// .h文件
#define LYSingletonH + (instance)sharedInstance;
// .m文件
#define LYSingletonM \
static id _instance; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
                 _instance = [super allocWithZone:zone] \
        }); \
        return _instance; \
} \
\
+ (instancetype)sharedInstance \
{ \
        static dispatch_once_t onceToken; \
        dispatch_once(&onceToken, ^{ \
                _instance = [super allocWithZone:zone]; \
        }); \
        return _instance; \
} \
 \
- (id)copyWithZone:(NSZone *)zone \
{ \
        return _instance; \
}

二、加锁实现

static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
        @synchronized(self) {
                if (_instance == nil) {
                        _instance = [super allocWithZone:zone];
                }
        }
        return _instance;
}
+ (instancetype)sharedInstance
{
        @synchronized(self) {
                if (_instance == nil) {
                        _instance = [super allocWithZone:zone];
                }
        }
        return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
        return _instance;
}

附:


相关文章

  • iOS 单例

    单例模式实现不能使用继承 定义单例实现 简写 定义单例实现宏

  • iOS 单例模式 - 单例对象销毁【@synchronized】

    单例对象的创建方式 单例.h 文件的实现 单例.m 文件的实现 单例对象的销毁【@synchronized创建方式...

  • iOS 单例模式 - 单例对象销毁【GCD】

    单例对象的创建方式 单例.h 文件的实现 单例的.m 文件的实现 单例对象的销毁【GCD创建的方式】 使用单例对象...

  • python面试题-2018.1.30

    问题:如何实现单例模式? 通过new方法来实现单例模式。 变体: 通过装饰器来实现单例模式 通过元类来创建单例模式...

  • 单例模式

    一、实现单例模式 或者 二、透明的单例模式 三、用代理实现单例模式 四、JavaScript中的单例模式 在Jav...

  • 单例模式

    饿汉模式: 懒汉模式: Double CheckLock(DCL)实现单例 静态内部类实现单例 枚举单例 使用容器...

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • kotlin实现单例模式

    1.懒汉式实现单例模式 2.线程安全懒汉式实现单例模式 3.双重校验懒汉式实现单例模式 4.静态内部类方式实现单例模式

  • 单例模式和GCD单例实现

    1、传统单例模式2、GCD单例模式3、用宏实现GCD单例模式4、用宏实现GCD单例模式,名称随类名变化而变化 单例...

  • 单例模式之枚举类enum

    通过枚举实现单例模式 枚举类实现单例模式的优点 对于饿汉式单例模式和懒汉式单例模式了解的同学,使用以上两种单例模式...

网友评论

      本文标题:单例的实现

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