iOS 單例模式
阿新 • • 發佈:2017-06-12
構造 使用 com htm bsp -c div 靜態 end
1、為單例對象實現一個靜態實例,並初始化,然後設置成nil,
2、實現一個實例構造方法檢查上面聲明的靜態實例是否為nil,如果是則新建並返回一個本類的實例,
3、重寫allocWithZone方法,用來保證其他人直接使用alloc和init試圖獲得一個新實力的時候不產生一個新實例,
4、適當實現copyWithZone,release和autorelease。 單例模式的實現:
“單例模式”是我在iOS中最常使用的設計模式之一。單例模式不需要傳遞任何參數,就有效地解決了不同代碼間的數據共享問題。單例類是一個非常重要的概念,因為它們表現出了一種十分有用的設計模式。單例類的應用貫穿於整個iOS的SDK中。例如,UIApplication類有一個方法叫sharedApplication,從任何地方調用這個方法,都將返回與當前正在運行的應用程序相關聯的UIApplication實例。除了這個,NSNotificationCenter(消息中心) 、NSFileManager(文件管理) 、 NSUserDefaults(應用程序設置) 、NSURLCache(請求緩存)、NSHTTPCookieStorage(應用程序cookies池)都是系統單例;單例類保證了應用程序的生命周期中有且僅有一個該類的實例對象,而且易於外界訪問。
單例模式的要點:
一是某個類只能有一個實例;二是它必須自行創建這個實例;三是它必須自行向整個系統提供這個實例。
單例模式的優點:
1.實例控制:Singleton 會阻止其他對象實例化其自己的 Singleton 對象的副本,從而確保所有對象都訪問唯一實例。 2.靈活性:因為類控制了實例化過程,所以類可以更加靈活修改實例化過程 IOS中的單例模式: 在objective-c中要實現一個單例類,至少需要做以下四個步驟:1、為單例對象實現一個靜態實例,並初始化,然後設置成nil,
2、實現一個實例構造方法檢查上面聲明的靜態實例是否為nil,如果是則新建並返回一個本類的實例,
3、重寫allocWithZone方法,用來保證其他人直接使用alloc和init試圖獲得一個新實力的時候不產生一個新實例,
4、適當實現copyWithZone,release和autorelease。 單例模式的實現:
代碼示例:
MySingletonClass.h
#import <Foundation/Foundation.h> @interface MySingletonClass : NSObject //單例方法
+(MySingletonClass *)sharedInstance; @end
MySingletonClass.m
#import "MySingletonClass.h" @implementation MySingletonClass //1、為單例對象實現一個靜態實例,並初始化,然後設置成nil, static MySingletonClass *manager = nil; //2、實現一個實例構造方法檢查上面聲明的靜態實例是否為nil,如果是則新建並返回一個本類的實例, +(MySingletonClass *)sharedInstance{ @synchronized(self) { if(manager == nil) { manager = [[MySingletonClass alloc] init]; // assignment not done here } } return manager; } //3、重寫allocWithZone方法,用來保證其他人直接使用alloc和init試圖獲得一個新實力的時候不產生一個新實例, +(id)allocWithZone:(NSZone *)zone{ @synchronized(self){ if (!manager) { manager = [super allocWithZone:zone]; //確保使用同一塊內存地址 return manager; } return nil; } } //4、適當實現copyWithZone,release和autorelease。 - (id)init; { @synchronized(self) { if (self = [super init]){ return self; } return nil; } } //確保copy對象也是唯一 - (id)copyWithZone:(NSZone *)zone;{ return self; }
本文示例源碼下載:http://www.oschina.net/code/snippet_2337537_52413
參考鏈接:
http://www.cnblogs.com/lyanet/archive/2013/01/11/2856468.html
http://blog.sina.com.cn/s/blog_71715bf80101a8mm.html
iOS 單例模式