The singleton design pattern is exactly one instance of a class that has a global interface to access this instance. When loaded for the first time, it typically creates a singleton using a deferred-loading method.
提示:苹果大量的使用了这种方法。例子:[NSUserDefaults standerUserDefaults], [UIApplication sharedApplication], [UIScreen mainScreen], [NSFileManager defaultManager] 都返回一个单一对象。
You might want to know why you care about a class that has multiple instances. Code and memory are cheap, aren't they?
In some cases, only one instance of a class is meaningful. For example, there is no need to have more than one login instance, unless you want to write more than one log file at a time. Or, a global configuration class file: It can be very safe to execute a common resource, such a configuration file is much better than modifying multiple configuration class files at the same time.
How to use singleton mode
Take a look at the picture below
The picture above shows a login class with a property (this single instance), with two methods: Sharedinstance and init.
First, a client sends sharedinstance information, but the attribute instance is not initialized, so you need to create an instance of the class first.
Then you call Sharedinstance,instance to return the initialized value immediately. This logic will eventually return only one instance.
You need to execute this pattern to create a singleton class to manage all the album data.
You need to be aware that in the project there is a folder called API, and all the classes that serve your APP need to be placed here. Create a new class in this folder with Ios\cocoa Touch\object-c class. The name of the class is called Libraryapi, and the subclass chooses NSObject.
Open the LibraryAPI.h file and replace the contents with the following code:
@interface LibraryAPI: NSObject+ (LibraryAPI*)sharedInstance;@end
Now open the LIBRARYAPI.M file and add the following method after the @implentation:
+ (LibraryAPI*)sharedInstance { // 1 static LibraryAPI *_sharedInstance = nil; // 2 static dispatch_once_t oncePredicate; // 3 dispatch_once(&nocePredicate, ^{ _sharedInstance = [[LibraryAPI alloc] init]; }); return _sharedInstance;}
In this short method of doing these things:
In this class, declare a static variable to hold the instance, ensuring that it is a globally available variable.
Declares a static this is dispatch_one_t, ensuring that these initialization code can only be executed once.
Use the Grand Central Dispatch (GCD) to execute a block to initialize the LIBRARYAPI instance. This is the key to a singleton design pattern: A class can only be instantiated once.
Following execution of Sharedinstance, the code in the Dispatch_once block will not be executed (once it has been executed once), it will return the LIBRARYAPI instance created earlier.
提示:想了解更多关于 GCD 和使用它,请点击这里的教程 Multithreading and Grand Central Dispatch,如何使用 Blocks 在这里。
You now have a single object to manage the album. The next step is to create a class to hold your album data.
Use the Ios\cocoa touch\object-c class to create a new class in the API folder, named Persistencymanager, the subclass select NSObject.
Open the PersistencyManager.h and introduce the polygon file at the top:
#import "Album.h"
Then add the following code after the @interface:
- (NSArray *)getAlbums;- (void)addAlbums:(Album*)album atIndex:(int)index;- (void)deleteAlbumAtIndex:(int)index;
The three methods above need to be combined with the album's data.
Open PERSISTENCYMANAGER.M and add the following code to the @implementation:
@interface PersistencyManager () { NSMutableArray *albums;}
The above code adds an extension to the class, which is another way to add private methods and private properties to the class, and members outside of the class do not see them. Here, you declare a Nsmutablearray to save the album's data. This is a mutable array, and you can easily add and delete albums.
Now add the implementation code below the @implementation:
-(ID) init {self = [super init]; if (self) {albums = [Nsmutablearray arraywitharray:@[[[album alloc] initwithtitle:@ "Best of Bowie" artist:@ "David Bowie "coverurl:@" Http://www.coversproject.com/static/thumbs/album/album_david%20bowie_best%20of%20bowie.png " year:@ "1992"], [[Album alloc] initwithtitle:@ "It ' s My life" artist:@ "No Doubt" coverurl:@ "http://www.coversproject. Com/static/thumbs/album/album_no%20doubt_its%20my%20life%20%20bathwater.png "year:@" 2003 "], [[album Alloc] initwithtitle:@ "Nothing Like the Sun" artist:@ "Sting" coverurl:@ "http://www.coversproject.com/static/thumbs/album/ Album_sting_nothing%20like%20the%20sun.png "year:@" 1999 "], [[album Alloc] initwithtitle:@" Staring at the Sun "a rtist:@ "U2" coverurl:@ "Http://www.coversproject.com/static/thumbs/album/album_u2_staring%20at%20the%20sun.png" year:@ "[[Album alloc] initwithtitle:@" American Pie "artist:@" Madonna "coverurl:@" http://www.coversp Roject.com/statIc/thumbs/album/album_madonna_american%20pie.png "year:@" 2000 "]]; } return self;}
In init you added 5 albums to the array. If the album above you do not like, you can feel free to replace it as you like. :]
Existing in PERSISTENCYMANAGER.M add the following three methods:
- (NSArray*)getAlbums{ return albums;}- (void)addAlbum:(Album*)album atIndex:(int)index{ if (albums.count >= index) [albums insertObject:album atIndex:index]; else [albums addObject:album];}- (void)deleteAlbumAtIndex:(int)index{ [albums removeObjectAtIndex:index];}
These methods are to get, add, and delete albums.
Build your project to make sure that all the code compiles correctly.
Now, you may wonder why there is a Persistencymanager class, because it is not a singleton class. Don't worry, the next step, the design pattern (facade Designs Patten) will explore the relationship between Libraryapi and Persistencymanager.
Design pattern Three: Single case mode singleton