设计模式:再严谨的单例也尽量不要使用

695 阅读1分钟

@(设计模式学习)

注意:

大多数的开发者都认同使用全局可变的状态是不好的行为。太多状态使得程序难以理解难以调试。不管什么情况下,我们都应该慎重考虑一下是否必须使用单例。单例应该只用来保存全局的状态,并且不能和任何作用域绑>定。如果这些状态的作用域比一个完整的应用程序的生命周期要短,那么这个状态就不应该使用单例来管理。

Objective-C实现

当我们调用单例的时候,不管是调用sharedInstance方法还是通过allocinit方法创建,或者copy一份,都应该保证在内存中只有一份实例。避免单例递归死锁

.h文件

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
@interface Singleton : NSObject
+(instancetype)sharedInstance;
@end
NS_ASSUME_NONNULL_END

.m文件

#import "Singleton.h"

@implementation Singleton
static Singleton *_instance = nil;
+(instancetype)sharedInstance {
    if (_instance) {
        return _instance;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (_instance) {
        return _instance;
    }
    return [super allocWithZone:zone];
}
-(id)copy {
    return self;
}
-(id)mutableCopy {
    return self;
}
@end

swift实现

class Singleton  {
    static let sharedInstance = Singleton()
    private init() {}
}

参考博客

避免滥用单例

Objective-C单例

swift单例