美文网首页
[iOS] 单例的各种写法

[iOS] 单例的各种写法

作者: CharlesQiu | 来源:发表于2017-11-03 11:59 被阅读37次

单例规则

  1. 单例必须是唯一的(要不怎么叫单例?) 在程序生命周期中只能存在一个这样的实例。单例的存在使我们可以全局访问状态。例如:

NSNotificationCenter, UIApplication和NSUserDefaults。

  1. 为保证单例的唯一性,单例类的初始化方法必须是私有的。这样就可以避免其他对象通过单例类创建额外的实例。

  2. 考虑到规则1,为保证在整个程序的生命周期中值有一个实例被创建,单例必须是线程安全的。并发有时候确实挺复杂,简单说来,如果单例的代码不正确,如果有两个线程同时实例化一个单例对象,就可能会创建出两个单例对象。也就是说,必须保证单例的线程安全性,才可以保证其唯一性。通过调用dispatch_once,即可保证实例化代码只运行一次。

Objective - C

@interface Kraken : NSObject
@end
 
@implementation Kraken
 
+ (instancetype)sharedInstance {
    static Kraken *sharedInstance = nil;
    static dispatch_once_t onceToken;
     
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Kraken alloc] init];
    });
    return sharedInstance;
}
 
@end

Swift

1. 最丑陋方法(Swift皮,Objective-C心)

class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: TheOneAndOnlyKraken? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = TheOneAndOnlyKraken()
        }
        return Static.instance!
    }
}

2. 结构体方法(“新瓶装老酒)

class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        struct Static {
            static let instance = TheOneAndOnlyKraken()
        }
        return Static.instance
    }
}

3.全局变量方法(“单行单例”方法)

private let sharedKraken = TheOneAndOnlyKraken()
class TheOneAndOnlyKraken {
    class var sharedInstance: TheOneAndOnlyKraken {
        return sharedKraken
    }
}

4. 最完美的

class TheOneAndOnlyKraken {
    static let sharedInstance = TheOneAndOnlyKraken()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}

原文地址

相关文章

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

  • [iOS] 单例的各种写法

    单例规则 单例必须是唯一的(要不怎么叫单例?) 在程序生命周期中只能存在一个这样的实例。单例的存在使我们可以全局访...

  • 单例的2种写法

    单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下: 1,常用写法 import "Se...

  • iOS-两种单例模式的实现

    单例模式是开发中最常用的写法之一,创建一个单例很多办法,iOS的单例模式有两种官方写法,如下: 不使用GCD 某些...

  • ios~单例模式:

    在iOS OC中,一般我们都是用官方推荐的写法来写单例:GCD方式单例 分析单例 static SharedPer...

  • ios 单例写法

  • 单例模式的各种写法

    引 好多码农写的最6的模式就是单例模式,其中也包括我。最先接触的设计模式也就是这个单例模式,后来随着业务拓展发现这...

  • iOS单例的写法

    参考https://www.jianshu.com/p/6b012ebc10fe .h文件 ```objectiv...

  • IOS单例的写法

    http://blog.sina.com.cn/s/blog_945590aa0102vxhb.html 可以看到...

  • iOS单例的写法

    1.互斥锁@synchroized(self) 可以重写allocWithZone方法,也可以再写一个类方法 2....

网友评论

      本文标题:[iOS] 单例的各种写法

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