single-case mode (Singleton)
Concept: An entire application or system can have only one instance of that class
In iOS development we often encounter situations where only one instance of a class is needed, the most common being the Access class for hardware parameters, such as Uiaccelerometer. This class can help us get the acceleration of the hardware in each direction axis, but we only need one instance of it enough, and then more, only waste memory.
Apple has used this mode extensively. For example: [Nsuserdefaults standarduserdefaults], [uiapplication sharedapplication], [UIScreen mainscreen], [NSFileManager Defaultmanager], all of these methods return a singleton object.
- The UIApplication class provides a +sharedapplication method for creating and retrieving UIApplication Singleton
- The NSBundle class provides a +mainbunle method for obtaining a nsbundle single case
- The Nsfilemanager class provides a +defaultmanager method for creating and obtaining Nsfilemanager singleton cases. (PS: Sometimes we have to give up using singleton mode and use the-init method to implement a new instance, such as when using a delegate)
- Nsnotificationcenter provides a +defaultcenter method for creating and retrieving Nsnotificationcenter Singleton (this class also follows another important design pattern: Observer mode)
- The Nsuserdefaults class provides a +defaultuserdefaults method to create and obtain Nsuserdefaults Singleton
Five steps to create a singleton pattern:
- Declares a method that can create and retrieve a single Instance object
- Declaring a class variable of type static
- Declare a task that executes only once
- Call Dispatch_once to execute the code block specified by the task, instantiating the class variable declared above in the code block
- Returns a variable that will only be instantiated once throughout the life of the app
The following code renders:
//Singleton.h@interfaceSingleton:nsobject+ (Singleton *) Sharedsingleton;//1 Declaring a method that can create and retrieve a single instance object@end /***************************************************************/ //singleton.m#import "Singleton.h"@implementationSingletonStaticSingleton *sharedsingleton = nil;//2 declaring a class variable of type static+ (Singleton *) sharedsingleton{Staticdispatch_once_t once;//3 Declaring a task that executes only onceDispatch_once (&once,^{Sharedsingleton= [[Self alloc] init];//call Dispatch_once to execute the code block specified by the task, instantiating the class variable declared above in the code block//dosometing }); returnSharedsingleton;//returns a variable that will only be instantiated once throughout the life of the application (not just once, but only once)}
practical use: Implement layered architecture design in iOS applications where we need to separate the data persistence layer, the business logic layer, and the presentation layer. (Persistencelayer, Businesslogiclayer, Presentationlayer)
Based on the MVC design pattern, we can also divide the persistence layer into the DAO layer (four kinds of methods for accessing data objects-adding and deleting) and the domain layer (various entity classes, such as date, text content, etc.) (Dao:data access Object data Access objects are an object-oriented interface)
Implementation: Encapsulates a single instance for initializing paths, files, etc.
//NoteDAO.h#import<Foundation/Foundation.h>#import "Note.h"@interfaceNotedao:nsobject+ (notedao*) sharedinstance;//Insert Note Method-(int) Create: (note*) model;//Delete Note Method-(int) Remove: (note*) model;//Modify the Note method-(int) Modify: (note*) model;//querying all data methods-(nsmutablearray*) FindAll;//querying data methods by primary key-(note*) FindByID: (note*) model;@end//NOTEDAO.M#import "NoteDAO.h"@interfaceNotedao ()//declaring Notedao extensions//The Dateformatter property in the Notedao extension is private@property (nonatomic,strong) NSDateFormatter*Dateformatter;//The property list file path in the sandbox directory in the Notedao extension is private (so it is not declared in the. h file)@property (nonatomic,strong) NSString*Plistfilepath;@end@implementationNotedaoStaticNotedao *sharedsingleton =Nil;+ (Notedao *) sharedinstance {Staticdispatch_once_t once; Dispatch_once (&once, ^{Sharedsingleton=[[Self alloc] init]; //Initialize the property list file path in the sandbox directorySharedsingleton.plistfilepath=[Sharedsingleton Applicationdocumentsdirectoryfile]; //Initialize DateformatterSharedsingleton.dateformatter=[[NSDateFormatter alloc] init]; [Sharedsingleton.dateformatter Setdateformat:@"YYYY-MM-DD HH:mm:ss"]; //initializing a property list file[Sharedsingleton createeditablecopyofdatabaseifneeded]; }); returnSharedsingleton;}//initializing a property list file- (void) createeditablecopyofdatabaseifneeded {... }-(NSString *) Applicationdocumentsdirectoryfile {}- (int) Create: (Note *) Model {... }-(nsmutablearray*) findall{}
Use this singleton in the business logic layer
notebl.m
#import " NoteBL.h " @implementation Notebl // Insert Note Method -(nsmutablearray*) Createnote: (note*) model { *dao = [Notedao sharedinstance ]; [DAO Create:model]; return
Single-instance mode for iOS learning