1.單例模式的作用
可以保證在程序運行過程,一個類只有一個實例,而且該實例易于供外界訪問
從而方便地控制了實例個數(shù),并節(jié)約系統(tǒng)資源
2.單例模式的使用場合
在整個應(yīng)用程序中,共享一份資源(這份資源只需要創(chuàng)建初始化1次)
3.單例模式在ARC\MRC環(huán)境下的寫法有所不同,需要編寫2套不同的代碼
可以用宏判斷是否為ARC環(huán)境
#if __has_feature(objc_arc)
//ARC
#else
//MRC
#endif
4.ARC中單利模式的代碼
#import <Foundation/Foundation.h>
@interface XMGPerson : NSObject
/** 名字 */
@property (nonatomic, strong) NSString *name;
+ (instancetype)sharedPerson;
@end
#import "XMGPerson.h"
@interface XMGPerson() <NSCopying>
@end
@implementation XMGPerson
static XMGPerson *_person;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [super allocWithZone:zone];
});
return _person;
}
+ (instancetype)sharedPerson
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [[self alloc] init];
});
return _person;
}
- (id)copyWithZone:(NSZone *)zone
{
return _person;
}
5.單例模式的封裝
XMGSingleton.h文件
// .h文件
#define XMGSingletonH + (instancetype)sharedInstance;
// .m文件
#define XMGSingletonM \
static id _instace; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)sharedInstance \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
}
調(diào)用方法
#import <Foundation/Foundation.h>
#import "XMGSingleton.h"
@interface XMGCar : NSObject
XMGSingletonH
@end
#import "XMGCar.h"
@implementation XMGCar
XMGSingletonM
@end
6.非GCD的單例模式
#import <Foundation/Foundation.h>
@interface XMGPerson : NSObject
+ (instancetype)sharedInstance;
@end
#import "XMGPerson.h"
@interface XMGPerson()
@end
@implementation XMGPerson
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance
{
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
@end
7.時間與空間的選擇
懶漢式是典型的以時間換取空間的例子,就是每次獲取實例時都要進(jìn)行判斷,看是否要創(chuàng)建實例,浪費判斷時間。當(dāng)然如果一直沒有人用的話,就不會創(chuàng)建實例,則是節(jié)約空間。而餓漢式是典型的以空間換取時間,就是說當(dāng)類裝載的時候,就創(chuàng)建出一個實例,不管你用不用它,然后每次調(diào)用時就不用判斷了,節(jié)省了運行時間。
下面這篇文章介紹了單例注意的問題:
http://www.nowamagic.net/librarys/veda/detail/1776