您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 單例模式詳解:四種寫法與線程安全實踐

編輯:iOS 開發綜合

單例模式是最常用的軟件設計模式之一。它的核心結構中只有一個被稱為「單例」的特殊類,作用是保證系統中某個類只有一個實例,且該實例易於被外界訪問,從而方便控制實例個數並節約系統資源。當你希望某個類的對象全局只存在一份時,單例就是最直接的方案。

一、書寫步驟

  1. 創建類方法,返回對象實例,命名慣例是以 shared / default / current 開頭。
  2. 創建一個全局(文件作用域)變量,用來保存該實例的引用。
  3. 在類方法中判斷實例是否存在,若不存在則創建。

二、四種實現方式

寫法一:非線程安全(僅作對照)

// 非線程安全寫法
static UserHelper *helper = nil;

+ (UserHelper *)sharedUserHelper
{
    if (helper == nil) {
        helper = [[UserHelper alloc] init];
    }
    return helper;
}

問題很明顯:若兩個線程同時通過 nil 判斷,就會各創建一個實例,單例被打破。單線程環境或確定不會併發訪問時可以用,但風險不值得冒。

寫法二:@synchronized 加鎖

// 線程安全寫法 1
static UserHelper *helper = nil;

+ (UserHelper *)sharedUserHelper
{
    @synchronized(self) {
        if (helper == nil) {
            helper = [[UserHelper alloc] init];
        }
    }
    return helper;
}

安全了,但每次調用都要獲取鎖,且在沒有競爭時也有開銷。

寫法三:重寫 +initialize

+ (void)initialize
{
    if ([self class] == [UserHelper class]) {
        helper = [[UserHelper alloc] init];
    }
}

+initialize 由運行時在類第一次收到消息前保證只調用一次,且是線程安全的。這裡的 if ([self class] == [UserHelper class]) 判斷必不可少——如果這個類被繼承,子類也會觸發一次 +initialize,不加判斷就會創建出第二個實例。

寫法四:dispatch_once(蘋果推薦)

// 線程安全寫法 3(蘋果推薦,實戰主要用這個)
static UserHelper *helper = nil;

+ (UserHelper *)sharedUserHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[UserHelper alloc] init];
    });
    return helper;
}

dispatch_once 由 GCD 提供,既保證只執行一次,又保證線程安全,性能也優於加鎖。這是目前公認的最佳實踐。

三、一個完整的 MRC 示例

下面是一個帶登錄狀態持久化的完整例子,可以直觀看到單例在真實場景中的用法。

#import <Foundation/Foundation.h>
#import "UserHelper.h"

int main(int argc, const char *argv[])
{
    @autoreleasepool {
        if ([UserHelper isLogin]) {
            UserHelper *helper = [UserHelper sharedUserHelper];
            NSLog(@"username = %@  password = %@", helper.userName, helper.password);
        } else {
            char name[20];
            char pwd[20];

            NSLog(@"請輸入用戶名");
            scanf("%s", name);
            NSLog(@"請輸入密碼");
            scanf("%s", pwd);

            NSString *userName = [[NSString alloc] initWithUTF8String:name];
            NSString *password = [[NSString alloc] initWithUTF8String:pwd];

            if (userName && password) {
                [UserHelper loginWithUserName:userName password:password];
                UserHelper *helper = [UserHelper sharedUserHelper];
                NSLog(@"username = %@  password = %@", helper.userName, helper.password);
            }
        }
    }
    return 0;
}
// UserHelper.h
#import <Foundation/Foundation.h>

@interface UserHelper : NSObject

// 1. 類方法,返回對象實例
+ (UserHelper *)sharedUserHelper;

@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *password;

+ (BOOL)isLogin;
+ (void)loginWithUserName:(NSString *)userName password:(NSString *)password;
+ (void)logout;

@end
// UserHelper.m
#import "UserHelper.h"

#define Path @"/Users/dahuan/Desktop/data"

// 2. 文件作用域的全局變量
static UserHelper *helper = nil;

@implementation UserHelper

+ (UserHelper *)sharedUserHelper
{
    // 3. 判斷是否存在,不存在則創建(這裡用 GCD 保證線程安全)
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[UserHelper alloc] init];
    });
    return helper;
}

- (instancetype)init
{
    if (self = [super init]) {
        // 首次創建時,嘗試從本地讀回上次登錄的信息
        NSString *data = [NSString stringWithContentsOfFile:Path
                                                  encoding:NSUTF8StringEncoding
                                                     error:nil];
        if (data) {
            NSArray *array = [data componentsSeparatedByString:@"-"];
            _userName = array[0];
            _password = array[1];
        }
    }
    return self;
}

+ (BOOL)isLogin
{
    UserHelper *helper = [UserHelper sharedUserHelper];
    if (helper.userName && helper.password) {
        return YES;
    }
    return NO;
}

+ (void)loginWithUserName:(NSString *)userName password:(NSString *)password
{
    UserHelper *helper = [UserHelper sharedUserHelper];
    helper.userName = userName;
    helper.password = password;

    // 持久化到本地
    NSArray *array = @[userName, password];
    NSString *data = [array componentsJoinedByString:@"-"];
    [data writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

+ (void)logout
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:Path]) {
        [fm removeItemAtPath:Path error:nil];
    }
}

@end

這個例子把單例的三個要素完整串了起來:類方法入口、全局變量存儲、初始化時的懶加載。同時也示範了單例最典型的用途——承載全局共享狀態(此處是登錄信息)。

四、什麼場景該用單例

合適的場景:全局配置管理、網絡請求客戶端、數據庫或 UserDefaults 封裝、日誌器、音頻播放器、定位管理等「天然全局唯一」的資源。iOS 系統裡的 UIApplication、NSUserDefaults、NSFileManager、NSNotificationCenter 都是單例。

不適合的場景:把大量互不相關的狀態都塞進一個「上帝單例」。這會讓單元測試變得困難(狀態無法隔離),也會讓依賴關係隱形化。實踐中更推薦按需拆分成多個職責單一的單例,必要時通過依賴注入傳遞。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved