1. Key points of the singleton mode:
It is obvious that there are three main points of the singleton pattern; one is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own.
2. Advantages of Singleton mode:
1. Instance control: Singleton prevents other objects from instantiating copies of their own Singleton objects, ensuring that all objects have access to unique instances. 2. Flexibility: Because classes control the instantiation process, classes can be more flexible in modifying the instantiation processSingleton mode in iOSTo implement a singleton class in objective-c, you need to do at least the following four steps:
1, for a singleton object to implement a static instance, and initialize, and then set to nil,
2. Implement an instance construction method to check if the static instance declared above is nil, and if it is new and returns an instance of this class,
3, rewrite the Allocwithzone method, to ensure that other people directly use Alloc and Init to try to gain a new strength when the time does not produce a new instance,
4, the appropriate implementation of Allocwithezone,copywithzone,release and Autorelease.It should be written like this, preventing yourself from Alloc.
staticMyGizmoClass *sharedGizmoManager =nil;
+ (MyGizmoClass*)sharedManager
{
if(sharedGizmoManager ==nil) {
sharedGizmoManager = [[superallocWithZone:NULL] init];
}
returnsharedGizmoManager;
}
+ (id)allocWithZone:(NSZone*)zone
{
return[[selfsharedManager] retain];
}
Most of the cases we write this way:
#import "FileOpration.h"
define a static variable
from the beginning of the definition to the end of the program
Static fileopration *instance = nil;
@implementation fileopration
+ (instancetype) sharedfileopration{
if (instance = = Nil) {
instance = [[fileopration alloc]init];
}
return instance;
}
@end
fileopration * F1 =[fileopration sharedfileopration];
fileopration * F2 =[fileopration sharedfileopration];
The following two are not possible to achieve a single case
fileopration * f3 =[[fileopration alloc]init];
fileopration * f4 =[[fileopration alloc]init];
Single-Case mode