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

iOS 開發中的單例類與半單例類:概念、實作與差異

編輯:iOS 開發綜合

設計模式中的「單例模式」對應到實作就是單例類。但在實際專案中,我們往往需要的其實是「半單例」。兩者的界線在哪裡,各自適用什麼情境,值得說清楚。

單例模式

顧名思義,單例就是只有一個實例。作為一種物件建立模式,它確保某個類別僅有一個實例,由該類自行建立並向整個系統提供這個實例。也就是說,無論外部嘗試建立多少次,永遠拿到同一個物件,且這個物件一定是全域可存取的。

Objective-C 中的完整實作

// Singleton.h
#import <Foundation/Foundation.h>

@interface Singleton : NSObject
+(id)shareInstance;
@end


// Singleton.m
#import "Singleton.h"

static Singleton *instance = nil;

@implementation Singleton

+(id)shareInstance {
    if (instance == nil) {
        instance = [[super allocWithZone:nil] init];
    }
    return instance;
}

+(id)allocWithZone:(NSZone *)zone {
    return [Singleton shareInstance];   // 攔截所有配置請求
}

- (id)init {
    if (instance) {
        return instance;                // 已有實例就直接回傳
    }
    self = [super init];
    return self;
}

-(id)copy {
    return self;
}
- (id)copyWithZone:(NSZone *)zone {
    return self;
}

-(id)retain {
    return self;
}
- (oneway void)release {
    // 什麼都不做
}
- (id)autorelease {
    return self;
}
- (NSUInteger)retainCount {
    return NSUIntegerMax;
}

@end

逐段解釋

static Singleton *instance = nil; 靜態全域變數,唯一指向那個實例。

+(id)shareInstance 是外界取得單例的唯一入口。instance 為 nil 時才建立,否則直接回傳,這就保證了唯一性。

-(id)copy / copyWithZone: 防止外部透過複製產生第二個實例。

-(id)retain 由於只有一個實例,retain 不應該讓引用計數增加。

- (NSUInteger)retainCount 回傳一個固定值(這裡取 NSUIntegerMax,也可以設成 1),讓外部查詢時不會誤判。

- (oneway void)release oneway void 是多執行緒分散式物件 API 的修飾詞,表示單向執行、不回滾,release 空實作能避免單例被意外釋放。

現代專案若使用 ARC,上述記憶體管理相關的覆寫大部分可省,只需保留 shareInstance 與 allocWithZone: 即可。

半單例

半單例與單例的關鍵差異有兩點:

  1. 它可以被建立多個實例。
  2. 系統要求能取得「當前那一個」實例。

典型的例子是 view controller:同一個類別可以被建立多份,但其中的子視圖在回呼時需要找到「目前這個」controller 來發送訊息。

以翻書程式為例

LeavesViewController 中放入多個 LeavesView 來實現多頁效果。當 LeavesView 判斷已翻到最後一頁,需要通知 controller 跳到下一個場景——此時 LeavesView 必須能找到當前的 LeavesViewController。

// LeavesViewController.h
#import <UIKit/UIKit.h>
#import "LeavesView.h"

@interface LeavesViewController : UIViewController <LeavesViewDataSource, LeavesViewDelegate> {
    LeavesView *leavesView;
}
@property(nonatomic, retain) LeavesView *leavesView;

+ (id)shareInstance;
- (void)goToPlay;
@end


// LeavesViewController.m
static LeavesViewController *leavesViewInstance = nil;

@implementation LeavesViewController
@synthesize leavesView;

- (id)init {
    if (self = [super init]) {
        leavesView = [[LeavesView alloc] initWithFrame:CGRectZero];
        leavesView.mode = UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
                            ? LeavesViewModeSinglePage
                            : LeavesViewModeFacingPages;
        leavesViewInstance = self;      // 關鍵:把自己記下來
    }
    return self;
}

- (void)dealloc {
    [leavesView release];
    leavesViewInstance = nil;           // 釋放全域變數,避免懸垂指標
    [super dealloc];
}

+ (id)shareInstance {
    if (leavesViewInstance == nil) {
        leavesViewInstance = [self init];
    }
    return leavesViewInstance;
}
@end

LeavesView 只是一個普通的視圖類別。當它偵測到已是最後一頁時:

if ([self hasNextPage] == NO) {
    NSLog(@"最後一頁!");
    [[LeavesViewController shareInstance] goToPlay];
}

透過 shareInstance 取得當前 controller,再送/goToPlay 訊息讓它回應。

兩者的界線

單例是「全系統只有一個」,適合管理全域資源,例如網路連線、資料庫、設定物件;半單例是「可以有很多個,但目前這一個是全域可知的」,適合視圖與控制器之間的溝通。

實作半單例時有一個必須注意的重點:dealloc 中一定要把靜態變數設回 nil。否則舊物件被釋放後,全域變數仍指向已失效的記憶體,下一次呼叫 shareInstance 就會得到懸垂指標而崩潰。這也是半單例比單例更容易出錯的地方。

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