Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. GOF presents 23 design patterns that will be implemented using swift language
Overview
For the entire application life cycle, only the classes that exist only one instance object are called 单例
, so the design of the module for common use of this object is called单例模式
The singleton pattern Singleton
has the following advantages:
- Multiple modules share the same object, guaranteeing the uniqueness of the data
- Unified logic function, with high flexibility
In the development of iOS, there are also many system singleton, such as NSNotificaitonCenter
Notification Center, UIApplication
application Singleton and so on, in swift, we mainly use two methods to create the singleton, usually I store the user data as a singleton to facilitate the access of different modules:
- Mode 1, declare static constants inside the class and privatize the constructor method
12345 |
class UserInfo { static let sharedinfo =< c12> UserInfo() Private init() {} } |
- Mode 2, using the global constant object
1234567 |
let singleton = UserInfo() class UserInfo { class var sharedinfo : UserInfo { return singleton }} |
For developers who have OC
turned around, the dispatch_once
Singleton created is more in line with their habits, but Swift3.0
after that the method itself is no longer available, and Apple static let
has used it in the implementation of the modified variable to ensure that the dispatch_once
variable exists only one copy.
Summarize
The singleton ensures that the data is unique during application operation and reduces the loss of repetitive memory, but it is also a burden if the single case itself is too large for memory consumption. On the other hand, the single-instance access also has the problem of multithreading security, which requires us to use the thread lock reasonably to guarantee the stability of the single case.
Swift Combat-single-case mode