Singleton mode : always returns the same instance of itself , which provides a global access point to the resources provided by the object of the class , and the returned instance can only be instantiated once.
There are two issues to be considered in the design of a single design pattern:
(1): An object that initiates a call cannot instantiate a singleton object in another assignment, or it is possible to create multiple instances of a singleton class
(2): The restriction on instantiation of singleton objects should coexist with the reference counting memory model.
Singleton.h
#import <Foundation/Foundation.h>
@interface Singleton:nsobject
+ (Singleton *) sharedinstance;
@end
Singleton.m
#import "Singleton.h"
@implementation Singleton
Static Singleton *sharedsingleton = nil;
+ (Singleton *) sharedinstance{
if (sharedsingleton = =nil) {
//sharedsingleton = [[Singleton alloc] init];
//--------->>>>> (1)
//sharedsingleton = [[Super Allocwithzone:null] init];
/*
The reason for using Super instead of self is that self has overloaded the allocwithzone method
so the allocation of memory is realized by invoking the method of the parent class.
In fact , the Allocwithzone method internally calls the Nsallocateobject method
*/
//--------->>>>> (2)
Sharedsingleton = [nsallocateobject([Self class], C7>0,NULL) init];
/*
The first parameter is type of Class
The second parameter is the extra number of bytes for the instance variable that is used for the index , always 0
The third parameter is used to specify the area allocated in memory , which is generally NULL, which is represented as the default zone
Not available here (1) and using (2) The reason for this is that processing, whether instantiated Singleton or sub-class , all applicable
*/
}
returnSharedsingleton;
}
/*
call the Allocwithzone of the class to pass in the Nszone parameter to allocate space for the new object that will be generated
The purpose of overloading is to not produce new instances when using the object's alloc method
because the Alloc method actually calls the Allocwithzone:null method, preventing other instances from being generated by Alloc
*/
+ (ID) Allocwithzone: (struct_nszone *) zone{
return [[self sharedinstance] retain];
}
/*
The purpose of overloading Copywithzone here is to prevent other instances from being generated when using the Copy method
*/
-(ID) Copywithzone: (nszone *) zone{
return self;
}
-(ID) retain{
return self;
}
-(nsuinteger) retaincount{
returnnsuintegermax;
}
-(void) release{
// do not do anything
}
-(ID) autorelease{
return self;
}
@end
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Single-instance mode for iOS design mode