The singleton pattern in this paper is divided into strict single case mode and not strict single case mode. The singleton pattern requires that a class have an instance that has a public interface that can access the instance. Strict singleton mode requires only one instance of a class; In case of strict singleton mode, multiple instances can be created.
Some classes can have only one instance, such as UIApplication, which accesses a unique instance through the shared property, and is a strict singleton pattern. In apps with user login, if the current user's data model differs from other users ' data models, the current user's class should also be in strict singleton mode. Logically, the current user has only one, only one instance, so that the current user's data can be accessed in various places. If the current user's data model is the same as another user's data model, the singleton mode is not strictly applied. You can create instances for other users, and you can access the current user's data in various places.
Swift implements strict singleton mode
Most objective-c classes inherit from NSObject, while Swift's classes can inherit from NSObject or do not inherit.
Inherit from NSObject
ClassSingletonclass:NSObject {StaticLet shared =Singletonclass ()Make sure the class have only one instanceshould not init or copy outsidePrivateOverrideInit () {}Overridefunc copy () any {return self //singletonclass.shared} override func mutablecopy () any {return self //singletonclass.shared} //Optional Span class= "hljs-function" >func reset () {//Reset all properties to default value}}
Static Properties Gkfx holds a unique instance that is exposed externally.
Overloads the Init () method so that it is not visible externally and cannot be called outside, preventing instances from being created externally.
Overloads the Copy (), Mutablecopy () method, and returns self to prevent the instance from being replicated externally. You can also return singletonclass.shared here, the effect is the same, because there is only one instance. Only GKFX can invoke the copy (), Mutablecopy () method, then self is shared. Write self, the code is relatively concise.
Once created, the singleton is held and cannot be destroyed manually, but the data can be reset. If necessary, you can add a method to reset the data reset (). For example, the current user exits the login and needs to reset all the properties of the current user instance to their default values to prevent data errors.
Do not inherit from NSObject
class SingletonClass2 { static let shared = SingletonClass2() // Make sure the class has only one instance // Should not init outside private init() {} // Optional func reset() { // Reset all properties to default value }}
Classes that do not inherit from NSObject do not have a copy (), Mutablecopy () method, and do not require overloading. Other ibid.
Not strict single case mode
You can create multiple instances by removing the overloaded init () method, or by removing private. If inherited from NSObject, Reload copy (), Mutablecopy () method: Creates a new instance, passes the data to the new instance, and returns a new instance. The other is the same as the strict singleton pattern.
Less rigorous method of resetting data
If the singleton has many properties, resetting the data requires that each property be changed to a default value, then the Reset () method writes a lot. There is an uncomfortable way to reset data: Regenerate an instance and assign a value to the static variable that holds the instance.
class SINGLETONCLASS3 {private static var _shared = SINGLETONCLASS3 () static var shared : SINGLETONCLASS3 {return _shared} Private init () {} //not safe //We Can obtain more than one instance outside with this function func reset () {singletonclass3._shared = Span class= "Hljs-type" >singletonclass3 ()}}
If the external access singleton is passed through the shared property, it will not be an error to write. However, if a singleton is held externally, it is possible to make an error.
let s = SingletonClass3.shareds.reset()print(s === SingletonClass3.shared) // false
The above output false,s after reset, and singletonclass3.shared is not the same object. Therefore, this method of resetting data is not rigorous. Or you should honestly assign each property as its default value.
OBJECTIVE-C implementation of a strict single case mode
. h file
@interface SingletonClassOC : NSObject+ (nonnull instancetype)shared;@end
. m file
@implementation SingletonclassocStaticID _shared;+ (nonnull instancetype) shared {if (!_shared) {_shared = [[Self alloc] init]; }return _shared;} + (Instancetype) Allocwithzone: (struct _Nszone *) Zone {Staticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{_shared = [Super Allocwithzone:zone]; });return _shared;} -(instancetype) init {Staticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{_shared = [Super Init]; });return _shared;} -(id) Copywithzone: (nszone *) zone {return self; //_shared}-(id) Mutablecopywithzone: ( Span class= "hljs-built_in" >nszone *) zone {return < Span class= "Hljs-keyword" >self; //_shared}//Optional-( void) reset {//Reset All Properties to default Value} @end
Static variable _shared holds a unique instance that is exposed externally through the shared method. In this method, if the _shared is found to be uninitialized, it is initialized. The nonnull of the return value of the method indicates that the return value is not NULL, which makes it convenient for Swift invocation. The return value of the non-nonnull,shared method in Swift is optional type (SINGLETONCLASSOC?), inconvenient to use, and nonnull is the SINGLETONCLASSOC type.
Overloaded Allocwithzone: And the Init method, the Dispath_once guarantees that the parent class method executes only once and assigns a value to _shared, returning _shared. The external call initialization method always obtains the only instance that _shared holds.
Overload Copywithzone: And Mutablecopywithzone: Method, return self to prevent the instance from being copied externally. Since there is only one instance _shared, the copy, Mutablecopy method can only be called by _shared, then self is _shared.
If necessary, reset the data with the Reset method.
Not strict single case mode
. h file
@interface SingletonClassOC2 : NSObject+ (nonnull instancetype)shared;@end
. m file
@implementation singletonclassoc2+ (nonnull instancetype) shared {StaticID _shared;Staticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{_shared = [[Self alloc] init]; });return _shared;} - (ID) Copywithzone: (nszone *) Zone {SingletonClassOC2 *copiedobject = [[self.class Allocwithzone:zone] init]; //Copy data to Copiedobject return Copiedobject;} -(id) Mutablecopywithzone: (nszone *) Zone { SingletonClassOC2 *copiedobject = [[self.class Allocwithzone:zone] Init ]; //Copy data to Copiedobject return Copiedobject;} -(void) reset {//Reset All properties to default Value} @end
Returned to an instance of external access through the shared method. Static variable _shared does not need to be used by multiple methods, so it can be written in a shared method. The _shared is guaranteed to be initialized only once by Dispatch_once.
Without overloading Allocwithzone: And the Init method, you can create a new instance externally. The Init method can be overloaded on demand, where initialization parameters are used, and so on, like classes that are not singleton patterns, calling the parent class method and finally returning self.
Overload Copywithzone: And Mutablecopywithzone: Method, create a new instance inside, pass the data to the new instance, return the new instance. Externally, you can copy an instance by using the copy or Mutablecopy method.
Not strict single case mode in Sdwebimage
The NSObject class method new is equivalent to the Alloc and Init methods.
Reprint Please specify source: http://www.cnblogs.com/silence-cnblogs/p/6776217.html
Swift, objective-c single-case mode (Singleton)