Singleton.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Singleton : NSObject
// 单例模式
+ (instancetype)shareSingleton;
@end
NS_ASSUME_NONNULL_END
Singleton.m
#import "Singleton.h"
@implementation Singleton
// 单例类的静态实例对象,因对象需要唯一性,故只能是static类型
static Singleton *_defaultManager = nil;
/**
单例模式对外的唯一接口,用到的dispatch_once函数在一个应用程序内只会执行一次,且dispatch_once能确保线程安全
*/
+ (instancetype)shareSingleton {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_defaultManager == nil) {
_defaultManager = [[self allocWithZone:nil] init];
}
});
return _defaultManager;
}
/**
覆盖该方法主要确保当用户通过[[Singleton alloc] init]创建对象时对象的唯一性,alloc方法会调用该方法,只不过zone参数默认为nil,因该类覆盖了allocWithZone方法,所以只能通过其父类分配内存,即[super allocWithZone:zone]
*/
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_defaultManager = [super allocWithZone:zone];
});
return _defaultManager;
}
// 覆盖该方法主要确保当用户通过copy方法产生对象时对象的唯一性
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
return [[self class] shareSingleton];
}
// 覆盖该方法主要确保当用户通过mutableCopy方法产生对象时对象的唯一性
- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {
return [[self class] shareSingleton];
}
@end
网友评论