设计模式-单例

2017/07/15 设计模式

Objective-C

/**
 *  分析代码:
 利用了static关键字,这样以来该变量就会一直存储在静态区的,和系统同生共死.
 利用gcd保证 instance = [[self alloc] init];这句代码只会执行一次,也就说明该对象一旦创建出来,就不会被重新创建
 */
static id instance; // 单例(全局变量)

/** 单例方法 */
+ (instancetype)shared<#Class#> {
    // 使用GCD确保只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

/** alloc 会调用allocWithZone方法 */
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    // 使用GCD确保只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

/** copy在底层 会调用copyWithZone方法 */
- (id)copyWithZone:(struct _NSZone *)zone {

    return instance;
}

Search

    Table of Contents