美文网首页
单例模式-iOS

单例模式-iOS

作者: 雨林QiQi | 来源:发表于2021-03-10 15:05 被阅读0次

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

iOS单例模式创建

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

调用验证

- (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>

相关文章

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

  • iOS 单例模式 or NSUserDefaults

    本文内容:iOS的单例模式NSUserDefaults的使用总结:iOS单例模式 and NSUserDefaul...

  • 单例模式 Singleton Pattern

    单例模式-菜鸟教程 iOS中的设计模式——单例(Singleton) iOS-单例模式写一次就够了 如何正确地写出...

  • 【设计模式】单例模式

    学习文章 iOS设计模式 - 单例 SwiftSingleton 原理图 说明 单例模式人人用过,严格的单例模式很...

  • iOS模式设计之--创建型:1、单例模式

    iOS模式设计之--1、单例模式

  • iOS单例模式容错处理

    ios 单例模式容错处理 1、单例模式的使用和问题解决 在ios开发的过程中,使用单例模式的场景非常多。系统也有很...

  • 谈一谈iOS单例模式

    这篇文章主要和大家谈一谈iOS中的单例模式,单例模式是一种常用的软件设计模式,想要深入了解iOS单例模式的朋友可以...

  • iOS知识梳理3:设计模式

    iOS有哪些常见的设计模式?单例模式/委托模式/观察者模式/MVC模式 单例模式 单例保证了应用程序的生命周期内仅...

  • 单例对象

    iOS单例模式(Singleton)单例模式的意思就是:只有一个实例;单例模式确保每个类只有一个实例,而且自行实例...

网友评论

      本文标题:单例模式-iOS

      本文链接:https://www.haomeiwen.com/subject/ziuwqltx.html