欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例的实现方式

程序员文章站 2022-07-13 23:42:22
...

第一种: GCD实现 (推荐使用)

新建一个Person类,在.h文件中添加方法

@interface Person : NSObject
+(instancetype)sharePerson;
@end

在.m文件中添加方法

#import "Person.h"
@interface Person()
@end
@implementation Person

static Person *_person;

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [super allocWithZone:zone];
    });
    return _person;
}

+ (instancetype)sharePerson{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [[super alloc] init];
    });
    return _person;
}

- (id)copyWithZone:(NSZone *)zone{
    return _person;
}
@end

第二种: 通过重写类方法实现

新建一个Person类,在.h文件中添加方法

@interface Person : NSObject

+ (instancetype)sharePerson;

@end

在.m文件中添加方法

#import "Person.h"

@implementation Person
static Person *_person;

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    @synchronized (self) {
        if (_person == nil) {
            _person = [super allocWithZone:zone];
        }
    };
    return _person;
}

+ (instancetype)sharePerson{
    @synchronized (self) {
        if (_person == nil) {
            _person = [[super alloc] init];
        }
    }
    return _person;
}

- (id)copyWithZone:(NSZone *)zone{
    return _person;
}
@end

注:

  1. 在第二种创建单例中, 必须对重写方法进行加锁, 因为考虑到线程安全问题,如果不加锁, 可能两个线程同时访问, 就会出现分配两个内存空间的情况..
  2. 单例的实现不能使用继承, 这样会造成所有继承的单例都是同一个对象

转载于:https://www.jianshu.com/p/d2139c5ae72d