iOS Developer

单例设计模式

2016-12-17  本文已影响28人  Coder007

单例设计模式

static SoundTool *_instance = nil;
+ (instancetype)shareSoundTool
{
    SoundTool *instance = [[self alloc] init];
    return instance;
}

+ (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;
}

// MRC
#if !__has_feature(objc_arc)
- (oneway void)release
{
}

- (instancetype)retain
{
    return _instance;
}

- (NSUInteger)retainCount
{
    return  MAXFLOAT;
}
 
- (instancetype)autorelease
{
    return self;
}
#endif

单例可以定义成宏

// .h文件中方法声明
#define interfaceSingleton(name)  +(instancetype)share##name

// .m文件中方法实现
#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  \
static name *_instance = nil; \
+ (instancetype)share##name \
{ \
    name *instance = [[self alloc] init]; \
    return instance; \
} \
+ (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; \
}
#else
// MRC

#define implementationSingleton(name)  \
static name *_instance = nil; \
+ (instancetype)share##name \
{ \
    name *instance = [[self alloc] init]; \
    return instance; \
} \
+ (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; \
} \
- (oneway void)release \
{ \
} \
- (instancetype)retain \
{ \
    return _instance; \
} \
- (NSUInteger)retainCount \
{ \
    return  MAXFLOAT; \
}\
- (instancetype)autorelease\
{\
    return self;\
}
#endif
上一篇 下一篇

猜你喜欢

热点阅读