the meaning and design of single case model
The singleton mode is a very simple design concept, which is more common in design mode. Singleton mode can be used when a class in your application has only one instance or object for external access. For example, the notification hubs in the messaging mechanism, or UIWindow in the UI interface, can be designed using a singleton pattern.
Singleton mode can provide a unique object for other classes to access, in object-oriented thinking, can make the whole program look more orderly, and can save memory space, because once the singleton is created, will always exist, other classes will access this unique instance.
#import <Foundation.Foundation.h>
@interface Singletonpattern:nsobject
{
@public
NSString *name; Design a property for a singleton to test if only a unique object exists
}
+ (Singletonpattern *) Single;
@end
#import "SingletonPattern.h"
@implementation Singletonpattern
+ (Singletonpattern *) Single
{
Static Singletonpattern *single; Declaring a Singleton object
if (!single)//If the Singleton object does not exist
{
Single =[[Singletonpattern alloc] init]; To create a new singleton object
}
return single; Return to the created instance
}
@end
Let's write another class to access the object and test if there is only one instance
#import <Foundation.Foundation.h>
@interface Test:nsobject
{
}
-(void) test;
@end
#import "Test.h"
#import "SingletonPattern.h"//Import a single case header file
@implementation Test
-(void) test
{
Singletonpattern *single = [Singletonpattern single]; Using the Singleton class method
NSLog (@ "%@", single, name); To access the properties of a singleton, but not assign a value to it
}
#import <Foundation.Foundation.h>
#import "SingletonPattern.h"
#import "Test.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
Singletonpattern *single = [Singletonpattern single];
Single, name = @ "ABC";
Test *test1= [[Test alloc] init];
[Test1 test];
}
return 0;
}
The result of the operation can be seen that the output is not nil, but the ABC given in the main function, you can conclude that the Singletonpattern class has only one instance object.
The design of a singleton mode in iOS