iOS 单利模式

2019-07-14  本文已影响0人  一直很安静_25ae

单利模式

单例模式的作用

单例模式的使用场合
-在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)


ARC中,单例模式的实现

在.m中保留一个全局的static的实例
static id _instance;

重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

提供1个类方法让外界访问唯一的实例

实现copyWithZone:方法


#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;
//因为alloc内部会调用allocWithZone
+ (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;
}
@end

单利模式提示宏

// .h文件
#define XMGSingletonH(name) + (instancetype)shared##name;

// .m文件
#define XMGSingletonM(name) \
static id _instance; \
 \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
} \
 \
+ (instancetype)shared##name \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[self alloc] init]; \
    }); \
    return _instance; \
} \
 \
- (id)copyWithZone:(NSZone *)zone \
{ \
    return _instance; \
}

单利模式宏的使用

#import <Foundation/Foundation.h>
#import "XMGSingleton.h"

@interface XMGPerson : NSObject
/** 名字 */
@property (nonatomic, strong) NSString *name;

XMGSingletonH(Person)
@end
#import "XMGPerson.h"

@interface XMGPerson()

@end

@implementation XMGPerson
XMGSingletonM(Person)
@end
#import "ViewController.h"
#import "XMGPerson.h"
@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
 [XMGPerson sharedPerson];
}

@end

非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
上一篇 下一篇

猜你喜欢

热点阅读