Single-Case mode
The singleton pattern is the simplest of the design patterns, and even some schema masters do not call it a pattern, calling it an implementation technique, because the design pattern emphasizes the abstraction of the relationship between objects, whereas singleton patterns have only one object.
When you need only one instance to use singleton, such as UIApplication.sharedApplication()
, Windows Task Manager, the Recycle Bin can only exist at the same time.
Let's look at several implementations in Swift:
1.
import Foundationclass SingleOne { //单例 static let shareSingleOne = SingleOne()}
A word to be done, static commonsense. All the places used are the same
2.
ImportFoundationclass singletwo {//single case class func sharesingletwo ()->singletwo{struct singleton{static var oncetoken:dispatch_once_t = 0 Static var single:singletwo?} dispatch_once (&singleton.oncetoken,{singleton.single=sharesingletwo ()}) return singleton.single!}}
Use Dispatch_once to ensure that the code is executed only once
3.
import Foundation//全局的常量let single = SingleThree()class SingleThree { class var sharedInstance : SingleThree { return single }}
4.
import Foundationclass SingleFour { static var sharedInstance : SingleFour { struct Static { static let instance : SingleFour = SingleFour() } return Static.instance }}
Defining static constants within a method
Paper/Big stone cloth (Jane book author)
Original link: http://www.jianshu.com/p/230cc900948c
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".
Four ways Swift implements a single case