美文网首页
单例的一些写法c、oc、swift

单例的一些写法c、oc、swift

作者: devVector | 来源:发表于2017-12-04 20:22 被阅读0次

纯C环境下

  1. pthread_once
static void * shareApplicationInfo;

//初始化函数
void initApplicationInfo() {
    shareApplicationInfo = malloc(sizeof(1));
}

void * getApplicationInfo() {
    static pthread_once_t token = PTHREAD_ONCE_INIT;
    pthread_once(&token,&initApplicationInfo);
    return shareApplicationInfo;
}
  1. dispatch_once 需要引libdispatch库
  • block写法
NSObject * getOCApplicationInfo() {
    static NSObject * __shareOCApplicationInfo;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __shareOCApplicationInfo = [[NSObject alloc] init];
    });
    return __shareOCApplicationInfo;
}
  • block 函数指针写法 跟pthread_once用法相似
static NSObject * __shareOCApplicationInfo2;
void initOC2ApplicationInfo(void * context) {
    __shareOCApplicationInfo2 = [[NSObject alloc] init];
}
NSObject * getOC2ApplicationInfo() {
    static dispatch_once_t onceToken;
    dispatch_once_f(&onceToken, NULL, initOC2ApplicationInfo);
    return __shareOCApplicationInfo2;
}
  1. swift
  • 一般写法
public class MySwiftManager {
    var some: String? = ""
    
    fileprivate init() {}
}

public let mySwiftManager: MySwiftManager = MySwiftManager()
  • 一般写法2 兼容OC
public final class MySwiftManager2: NSObject {
    var some: String? = ""
    
    fileprivate override init() {
        super.init()
    }
    @objc public static let share: MySwiftManager2 = MySwiftManager2()
}

  • 可以在初始化完成后做一些事的写法
public final class MySwiftManager {
    var some: String? = ""
    
    fileprivate init() {}
}

public let mySwiftManager: MySwiftManager = {
    let value = MySwiftManager()
    value.some = "mySwiftManager"
    return value
}()

备注: 尽量让单例的init方法私有, 不要暴露出去,除非你确定需要这么做
tips: 如果是个单例 init 方法私有, 用final 修饰类
关于命名:单例用share(我们一般是用的这种模式), default 默认的实例, 我们可以自已再初始化实例。(参考UIApplication.shared , NotificationCenter.default)

相关文章

网友评论

      本文标题:单例的一些写法c、oc、swift

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