Singleton mode is used in the actual project development of a more than a design pattern, the design principle is that the whole system only produces an object instance, through a unified method to provide external use of this instance.
In Java, constructing a singleton typically declares the constructor of a class as private and then provides an instance object externally through a static method, so, in OC, see the complete code below for an example of how to implement a singleton.
@implementation Car
Declare a static object reference and assign nil
static Car *sharedinstance= Nil;
Declaring a class method (+ is a class method, that is, a static method in Java )
+ (Car *) sharedinstance
{
if (!sharedinstance)
{
Sharedinstance = [[Self alloc] init];
}
return sharedinstance;
}
@end
Override Allocwithzone: Method to prevent any class from creating a second instance. Use synchronized () to prevent multiple threads from executing the code at the same time (the thread lock)
+ (ID) Allocwithzone: (Nszone *) zone
{
@synchronized (self)
{
if (sharedinstance = = nil)
{
Sharedinstance = [Super Allocwithzone:zone];
return sharedinstance;
}
}
return sharedinstance;
}