iOS development singleton mode

1. What is the singleton pattern

Guarantee card system and a class has only one instance of this example provides global access to the inlet.

Common singleton use cases are:UIApplication(应用程序实例类) NSNotificationCenter(消息中心类) NSFileManager(文件管理类) NSUserDefaults(应用程序设置) NSURLCache(请求缓存类) NSHTTPCookieStorage(应用程序cookies池)

Second, the basic realization of the singleton pattern

#pragma mark === 单例
+(instancetype)sharedManager
{
    static TangLinHFNetWorkManager* manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
             manager=[[TangLinHFNetWorkManager alloc]init];
        }
    });
    return manager;
}

This is the singleton class that I usually use for network requests.

In order to prevent duplicate creation, there are two ways to solve: One is to directly disable his creation method, and then prompt an error message. The second is to rewrite several creation methods.

3. The advantages and disadvantages of the singleton model

advantage:

1. Provides controlled access to unique instances, is simple to use, and easy to cross modules.

2. Since there is only one object in the system memory, it can save system resources. For some objects that need to be frequently created and destroyed, the singleton mode can undoubtedly improve the performance of the system.

3. Because the singleton pattern class controls the instantiation process, the class can modify the instantiation process more flexibly.

Disadvantages:

1. Not easy to be rewritten or expanded

2. Cannot be inherited

3. The singleton exists as long as the program is not destroyed, consuming system memory resources

 

Guess you like

Origin www.cnblogs.com/laolitou-ping/p/12747045.html