1索昂、單例模式簡述
- 一個類有且僅有
一個實例
,并且自行實例化向整個系統(tǒng)提供员萍。
2促王、單例模式UML類圖
3犀盟、單例模式示意代碼
SingletonA
/********* SingletonA.h **********/
@interface YSingletonA : NSObject
+ (instancetype)sharedInstance;
@end
/********* SingletonA.m **********/
@implementation YSingletonA
static YSingletonA *_instance = nil;
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[[self class] alloc] init];
});
return _instance;
}
@end
/********* 使用 **********/
YSingletonA *singleton1 = [YSingletonA sharedInstance];
NSLog(@"%@", singleton1);
YSingletonA *singleton2 = [YSingletonA sharedInstance];
NSLog(@"%@", singleton2);
YSingletonA *singleton3 = [[YSingletonA alloc] init];
NSLog(@"%@", singleton3);
YSingletonA *singleton4 = [[YSingletonA alloc] init];
NSLog(@"%@", singleton4);
YSingletonA *singleton5 = [YSingletonA new];
NSLog(@"%@", singleton5);
YSingletonA *singleton6 = [YSingletonA new];
NSLog(@"%@", singleton6);
/*
運行結(jié)果:
<YSingletonA: 0x60000000b550>
<YSingletonA: 0x60000000b550>
<YSingletonA: 0x60c00000bc30>
<YSingletonA: 0x60400000b440>
<YSingletonA: 0x60400000b450>
<YSingletonA: 0x60c00000a9f0>
YSingletonA調(diào)用sharedInstance方法可以做到多次創(chuàng)建的實例是同一個
但是<無法做到>調(diào)用原有的init方法或者new方法創(chuàng)建的實例也是同一個
YSingletonA違背了單例類有且僅有一個實例的定義,或者說做的不夠完善
*/
- SingletonB
/********* SingletonB.h **********/
@interface YSingletonB : NSObject <NSCopying, NSMutableCopying>
+ (instancetype)sharedInstance;
@end
/********* SingletonB.m **********/
@implementation YSingletonB
static YSingletonB *_instance = nil;
+ (instancetype)sharedInstance {
return [[self alloc] init];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return _instance;
}
@end
/********* 使用 **********/
YSingletonB *singleton1 = [YSingletonB sharedInstance];
NSLog(@"%@", singleton1);
YSingletonB *singleton2 = [YSingletonB sharedInstance];
NSLog(@"%@", singleton2);
YSingletonB *singleton3 = [[YSingletonB alloc] init];
NSLog(@"%@", singleton3);
YSingletonB *singleton4 = [[YSingletonB alloc] init];
NSLog(@"%@", singleton4);
YSingletonB *singleton5 = [YSingletonB new];
NSLog(@"%@", singleton5);
YSingletonB *singleton6 = [YSingletonB new];
NSLog(@"%@", singleton6);
YSingletonB *singleton7 = [singleton5 copy];
NSLog(@"%@", singleton7);
YSingletonB *singleton8 = [singleton5 mutableCopy];
NSLog(@"%@", singleton8);
/*
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
<YSingletonB: 0x6080000069a0>
YSingletonB調(diào)用sharedInstance方法,alloc蝇狼,init方法阅畴,new方法,甚至包括copy迅耘、mutableCopy方法我們得到的都是用一個實例
*/