单例模式-iOS

这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。

iOS单例模式创建

VSingleton.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface VSingleton : NSObject

+ (instancetype)shareInstance;

@end

NS_ASSUME_NONNULL_END

VSingleton.m

#import "VSingleton.h"

@interface VSingleton ()

@end

static id singleton = nil;

@implementation VSingleton

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (singleton == nil) {
            singleton = [[super allocWithZone:NULL]init];
        }
    });
    return singleton;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [[self class] shareInstance];
}

- (id)copyWithZone:(NSZone *)zone {
    return [[self class]shareInstance];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [[self class]shareInstance];
}

@end

调用验证

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    VSingleton *test1 = [VSingleton shareInstance];
    VSingleton *test2 = [[VSingleton alloc]init];
    VSingleton *test3 = [test1 copy];
    VSingleton *test4 = [test1 mutableCopy];
    VSingleton *test5 = [VSingleton new];
    NSLog(@"test1:%@",test1);
    NSLog(@"test2:%@",test2);
    NSLog(@"test3:%@",test3);
    NSLog(@"test4:%@",test4);
    NSLog(@"test5:%@",test5);
}

输出

2021-03-10 15:05:07.273885+0800 LearnDemo[8363:142167] test1:
2021-03-10 15:05:07.274551+0800 LearnDemo[8363:142167] test2:
2021-03-10 15:05:07.274700+0800 LearnDemo[8363:142167] test3:
2021-03-10 15:05:07.274804+0800 LearnDemo[8363:142167] test4:
2021-03-10 15:05:07.274912+0800 LearnDemo[8363:142167] test5:

你可能感兴趣的:(单例模式-iOS)