iOS學習之單例模式

來源:互聯網
上載者:User

標籤:center   屬性   生命週期   ace   ring   nsobject   刪除   nsbundle   for   

單例模式(Singleton)

概念:整個應用或系統只能有該類的一個執行個體

在iOS開發我們經常碰到只需要某類一個執行個體的情況,最常見的莫過於對硬體參數的訪問類,比如UIAccelerometer.這個類可以協助我們獲得硬體在各個方向軸上的加速度,但是我們僅僅需要它的一個執行個體就夠了,再多,只會浪費記憶體。

蘋果大量使用了此模式。例如:[NSUserDefaults standardUserDefaults], [UIApplication sharedApplication], [UIScreen mainScreen], [NSFileManager defaultManager],所有的這些方法都返回一個單例對象。

  • UIApplication類提供了 +sharedAPplication方法建立和擷取UIApplication單例
  • NSBundle類提供了 +mainBunle方法擷取NSBundle單例
  • NSFileManager類提供了 +defaultManager方法建立和獲得NSFileManager單例。(PS:有些時候我們得放棄使用單例模式,使用-init方法去實現一個新的執行個體,比如使用委託時)
  • NSNotificationCenter提供了 +defaultCenter方法建立和擷取NSNotificationCenter單例(該類還遵循了另一個重要的設計模式:觀察者模式)
  • NSUserDefaults類提供了 +defaultUserDefaults方法去建立和擷取NSUserDefaults單例

建立單例模式的五個步驟:

  1. 聲明一個可以建立和擷取單個執行個體對象的方法
  2. 聲明一個static類型的類變數
  3. 聲明一個只執行一次的任務
  4. 調用dispatch_once執行該任務指定的代碼塊,在該代碼塊中執行個體化上文聲明的類變數
  5. 返回在整個應用的生命週期中只會被執行個體化一次的變數

下面用代碼呈現:

//Singleton.h@interface Singleton : NSObject+ (Singleton *)sharedSingleton; //1聲明一個可以建立和擷取單個執行個體對象的方法@end /***************************************************************/ //Singleton.m#import "Singleton.h"@implementation Singleton   static Singleton *sharedSingleton = nil;// 2聲明一個static類型的類變數 + (Singleton *)sharedSingleton{    static dispatch_once_t  once; //3聲明一個只執行一次的任務    dispatch_once(&once,^{        sharedSingleton = [[self alloc] init];// 調用dispatch_once執行該任務指定的代碼塊,在該代碼塊中執行個體化上文聲明的類變數        //dosometing    });    return sharedSingleton;// 返回在整個應用的生命週期中只會被執行個體化一次的變數(不止調用一次,但是只執行個體化一次)}

 

實際運用:在iOS應用中實現分層的架構設計,即我們需要把資料持久層,商務邏輯層,和展示層分開。(PersistenceLayer、 BusinessLogiclayer 、 PresentationLayer)

根據MVC的設計模式,我們又可以把持久層細分為DAO層(放置訪問資料對象的四類方法-增刪改查)和Domain層(各種實體類,比如日期,常值內容等)(DAO:Data Access ObjectData Access Objects是一個物件導向的介面)

實現:封裝一個單例,用於初始化路徑,檔案等

//  NoteDAO.h#import <Foundation/Foundation.h>#import "Note.h"@interface NoteDAO : NSObject+ (NoteDAO*)sharedInstance;//插入Note方法-(int) create:(Note*)model;//刪除Note方法-(int) remove:(Note*)model;//修改Note方法-(int) modify:(Note*)model;//查詢所有資料方法-(NSMutableArray*) findAll;//按照主鍵查詢資料方法-(Note*) findById:(Note*)model;@end//  NoteDAO.m#import "NoteDAO.h"@interface NoteDAO() //聲明NoteDAO擴充//NoteDAO擴充中DateFormatter屬性是私人的@property (nonatomic,strong) NSDateFormatter *dateFormatter;// NoteDAO擴充中沙箱目錄中屬性列表檔案路徑是私人的(所以不放在.h檔案中聲明)@property (nonatomic,strong) NSString *plistFilePath;@end@implementation NoteDAOstatic NoteDAO *sharedSingleton = nil;+ (NoteDAO *)sharedInstance {    static dispatch_once_t once;    dispatch_once(&once, ^{        sharedSingleton = [[self alloc] init];        //初始化沙箱目錄中屬性列表檔案路徑        sharedSingleton.plistFilePath = [sharedSingleton applicationDocumentsDirectoryFile];        //初始化DateFormatter        sharedSingleton.dateFormatter = [[NSDateFormatter alloc] init];        [sharedSingleton.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];        //初始化屬性列表檔案        [sharedSingleton createEditableCopyOfDatabaseIfNeeded];    });    return sharedSingleton;}//初始化屬性列表檔案- (void)createEditableCopyOfDatabaseIfNeeded {。。。}- (NSString *)applicationDocumentsDirectoryFile {}- (int)create:(Note *)model {。。。}-(NSMutableArray*) findAll{}

 

在商務邏輯層使用這個單例

//  NoteBL.m

#import "NoteBL.h"@implementation NoteBL//插入Note方法-(NSMutableArray*) createNote:(Note*)model {    NoteDAO *dao = [NoteDAO sharedInstance];    [dao create:model];    return [dao findAll];} 

 

iOS學習之單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.