单例模式(Singleton)
保证一个类仅有一个实例,并提供一个该实例的全局访问点。
定义包含三层含义:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须向整个系统提供这个实例。
OC
@interface ZZSingleton : NSObject
+ (instancetype)shareSingleton;
@end
@implementation ZZSingleton
static ZZSingleton *shareSingleton = nil;
+ (instancetype)shareSingleton {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareSingleton = [[super allocWithZone:NULL] init];
});
return shareSingleton;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [ZZSingleton shareSingleton];
}
- (id)copyWithZone:(struct _NSZone *)zone {
return [ZZSingleton shareSingleton];
}
@end
#######
ZZSingleton *one = [ZZSingleton shareSingleton];
NSLog(@"one = %@", one);
ZZSingleton *two = [ZZSingleton shareSingleton];
NSLog(@"two = %@", two);
ZZSingleton *three = [[ZZSingleton alloc] init];
NSLog(@"three = %@", three);
ZZSingleton *four = [[ZZSingleton alloc] init];
NSLog(@"four = %@", [four copy]);
ZZSingleton *five = [ZZSingleton new];
NSLog(@"five = %@", five);
网友评论