單例模式-iOS

這種類型的設(shè)計(jì)模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對(duì)象的最佳方式。這種模式涉及到一個(gè)單一的類,該類負(fù)責(zé)創(chuàng)建自己的對(duì)象,同時(shí)確保只有單個(gè)對(duì)象被創(chuàng)建。這個(gè)類提供了一種訪問(wèn)其唯一的對(duì)象的方式,可以直接訪問(wèn),不需要實(shí)例化該類的對(duì)象。
注意
1、單例類只能有一個(gè)實(shí)例。
2、單例類必須自己創(chuàng)建自己的唯一實(shí)例。
3、單例類必須給所有其他對(duì)象提供這一實(shí)例。

iOS單例模式創(chuàng)建

VSingleton.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface VSingleton : NSObject

+ (instancetype)shareInstance;

@end

NS_ASSUME_NONNULL_END

VSingleton.m

#import "VSingleton.h"

@interface VSingleton ()<NSCopying,NSMutableCopying>

@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

調(diào)用驗(yàn)證

- (void)touchesBegan:(NSSet<UITouch *> *)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:<VSingleton: 0x6000028807e0>
2021-03-10 15:05:07.274551+0800 LearnDemo[8363:142167] test2:<VSingleton: 0x6000028807e0>
2021-03-10 15:05:07.274700+0800 LearnDemo[8363:142167] test3:<VSingleton: 0x6000028807e0>
2021-03-10 15:05:07.274804+0800 LearnDemo[8363:142167] test4:<VSingleton: 0x6000028807e0>
2021-03-10 15:05:07.274912+0800 LearnDemo[8363:142167] test5:<VSingleton: 0x6000028807e0>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容