GCD与非GCD实现单粒设计模式

2015-07-15  本文已影响118人  zhazha

GCD实现设计模式

在某个类里面实现GCD单粒设计模式

@interface ZMJPerson : NSObject

+ (instancetype)sharedInstance;

@end
// 实例变量,当前类
static id _instance;

// 重写allocWithZone方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t onceToken;

    // 该方法整个应用程序只调用一次
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

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

// 保证每复制一个对象也是同一个内存空间
- (id)copyWithZone:(NSZone *)zone{
    return _instance;
}

宏定义封装GCD单粒设计模式(1)

// .h文件
#define ZMJSingletonH  + (instancetype)sharedInstance;

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

宏定义封装GCD单粒设计模式(2)

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

// .m文件
#define ZMJSingletonM(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;\
}

非GCD实现设计模式

@interface ZMJPerson : NSObject

+ (instancetype)sharedInstance;

@end
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;
}

注意点

上一篇下一篇

猜你喜欢

热点阅读