Home 002-实现“简单单例模式”的几种方法?
Post
Cancel

002-实现“简单单例模式”的几种方法?

首先不管哪种写法都要首先声明一个静态单例对象,如下所示:

1
static GNRSingleModel *instance = nil;

其次就是创建单例的时机了,常用的有以下几种写法:

一、简单写法(线程不安全)

1
2
3
4
5
6
7
+ (instancetype)sharedInstance{
    if (instance==nil) {
        instance = [[GNRSingleModel alloc]init];
    }
    return instance;
}

二、使用dispatch_once(线程安全)

1
2
3
4
5
6
7
+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[GNRSingleModel alloc]init];
    });
    return instance;
}

三、在initialize中创建(线程安全) 

1
2
3
4
5
+ (void)initialize{
    if (self == [super class]) {
        instance = [[GNRSingleModel alloc]init];
    }
}
This post is licensed under CC BY 4.0 by the author.

链式编程

001-浅拷贝和深拷贝的区别?