单例设计模式

2018-09-21  本文已影响0人  皆为序幕_

概念

一个类只允许有一个实例,在整个程序中需要多次使用,共享同一份资源的时候,就可以创建单例,一般封装成工具类使用,苹果封装成单例常用的有UIApplication,NSUserDefaults,NSNotificationCenter,NSFileManager等等

优缺点

实现

一般情况下创建一个单例对象都有一个与之对应的类方法
一般情况下用于创建单例对象的方法名都以share或default开头加上当前类名

static Person * _instance = nil;
+(instancetype) sharePerson{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance= [[self alloc] init];
    });
    return _instance;
}


Person *p = [Person sharePerson];
NSLog(@"p:%p",p);
Person *p1 = [[Person alloc]init];
NSLog(@"p1:%p",p1);

这种不能算是真正意义上的单例 ,因为类方法和alloc init创建的单例分配的内存可能不一样
p :0x600000c1da40
p1:0x600000c76c60

因为alloc会执行allocWithZone,所以如果想只分配一次内存就要重写此方法,同时为了严谨,防止copy出现以上问题,还要重写copyWithZonemutableCopyWithZone

+ (instancetype)sharePerson{
    Person *instance = [[self alloc]init];
    return instance;
}
static Person *_instance = nil;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    //由于所有的创建方法都会调用这个方法,所以只需要在该方法中控制当前对象只创建一次即可
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:zone]init];
    });
    return _instance;
}
-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}

Person *p = [Person sharePerson];
NSLog(@"p:%p",p);
Person *p1 = [[Person alloc]init];
NSLog(@"p1:%p",p1);

p :0x600001fb3700
p1:0x600001fb3700

宏定义单例

#define interfaceSinglenton(name) +(instancetype)share##name

#define implementationSinglenton(name)  \
+ (instancetype)share##name{ \
name *instance = [[self alloc]init]; \
return instance; \
} \
static name *_instance = nil; \
+(instancetype)allocWithZone:(struct _NSZone *)zone{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone]init]; \
}); \
return _instance; \
} \
-(id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
-(id)mutableCopyWithZone:(NSZone *)zone{ \
return _instance; \
} \

宏定义单例的使用

@interface Person : NSObject
@property (nonatomic,strong) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
interfaceSinglenton(Person);
@end

#import "Person.h"
@implementation Person
implementationSinglenton(Person);
@end


Person *p = [Person sharePerson];
NSLog(@"p :%p",p);
Person *p1 = [[Person alloc]init];
NSLog(@"p1:%p",p1);

log:
p :0x6000027bcb00
p1:0x6000027bcb00
上一篇下一篇

猜你喜欢

热点阅读