One, intent
II, usage scenario
Span style= "font-size:medium;" >1, use scene
When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.
2, important three steps to implement
privatization construction method (Swift not supported)
Iii. implementation of the Swift language
swift language does not support the permissions of variables and methods, there is no way to hide variables and methods, you can create an instance directly. The creation of a singleton has many formulations, Swift supports only structs that support static variables, and class does not support static variables, so it is easy to think that using a struct inside a class solves the problem of saving the reference, and the code is as follows:
- Class Swiftsingleton {
- class Var Shared:swiftsingleton {
- Dispatch_once (&inner.token) {
- Inner.instance = Swiftsingleton ()
- }
- Return inner.instance!
- }
- struct Inner {
- static Var Instance:swiftsingleton?
- static var token:dispatch_once_t = 0
- }
- }
Copy Code
Run the following test code for a simple test:
- Class Swiftsingletontest:xctestcase {
- Func Testsingleton () {
- Let Singleton1 = swiftsingleton.shared
- Let Singleton2 = swiftsingleton.shared
- ASSERT (Singleton1 = = = Singleton2, "pass")
- }
- }
Copy Code
Run the result, the green checkmark on the left represents the execution through:
where = = = "equivalent" in swift, comparing two variables or constant reference addresses, can only be used for class comparison
In Swift, the static type variable is automatically implemented as a lazy load mode, or it can be implemented as follows:
- Class Swiftsingleton {
- class Var Shared:swiftsingleton {
- Return inner.instance
- }
- struct Inner {
- static Let instance = Swiftsingleton ()
- }
- }
Copy Code
Iv. implementations that could cause errors
class is a very important difference from the struct:
class: The reference
struct: Value
- struct Swiftsingleton {
- var name:string = "1"
- static Let shared = Swiftsingleton ()
- }
- var single1 = swiftsingleton.shared
- var single2 = swiftsingleton.shared
- Single2.name = "2"
- println ("------->\ (single1.name)")
- println ("------->\ (single2.name)")
Copy Code
The printing results are as follows:
- ------->1
- ------->2
- Program ended with exit code:0
Copy Code
As can be seen from the above, through the implementation of the struct, we can not guarantee that there is only one instance, this implementation is problematic
A single example of the Swift design pattern (SINGLETON)