iOS 再谈单例的几种写法

作者: 圆脸黑猫警长 | 来源:发表于2016-06-30 15:26 被阅读480次

1.为什么再谈?

常规的单例写法有两种
+ (Student *)defaultInstance
{
static Student *defaultInstance = nil;
if (!defaultInstance)
{
defaultInstance = [[self alloc] init];
}
return defaultInstance;
}

+ (Student *)sharedManager
{
static Student *sharedInstance = nil;
static dispatch_once_t predicate;//此象必须是全局或者静态对象才能保证唯一性
dispatch_once(&predicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}

这两种写法的优缺点都是老生常谈,本文不再赘述。
这两种写法的最大问题其实是不能保证别人只通过这种方式获取该对象。若直接使用Student *std = [Student alloc] init];的方式去创建对象,则获取到的是一个新的对象。

2.解决方案

模仿UIApplication重写init方法。调用init时抛出异常,禁止别人调用。

  • 在.m文件中
    static Student *student = nil;

    + (void)load
    {
        student = [[self alloc] init];
    }
    
    //此方法和load选一个写即可,两个方法的区别下篇文章讲
    //+ (void)initialize
    //{
       // student = [[self alloc] init];
    //}
    
    + (instancetype)shareInstance
    {
        return student;
    }
    
    - (instancetype)init
    {
        if (student)
        {
            //抛异常
            NSException *exp = [NSException exceptionWithName:NSInternalInconsistencyException reason:@"There can only be one Student instance." userInfo:nil];
            [exp raise];
        }
        return [super init];
    }
    

如这样处理,在调用init时会抛出异常。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'There can only be one Student instance.'
.
.//省略无关内容
.
libc++abi.dylib: terminating with uncaught exception of type NSException

相关文章

  • iOS 再谈单例的几种写法

    1.为什么再谈? 常规的单例写法有两种+ (Student *)defaultInstance{static St...

  • iOS 单例模式

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

  • iOS 单例的几种写法

    1、不使用GCD的方式 2、使用GCD // 补充再来说说:Objective-C 里的 Alloc 和Alloc...

  • iOS单例的几种写法

    单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类...

  • 单例的2种写法

    单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下: 1,常用写法 import "Se...

  • iOS-单例的几种写法

    一、静态指针方式(单线程模式单例) 二、多线程加锁单例 三、单例的健壮性 由于水平有限,难免出现纰漏,如有问题还请...

  • 单例模式

    单例设计模式是几种设计模式中比较容易理解的,手写单例模式也是面试频繁问到的。下面总结一下单例模式的几种写法: //...

  • 几种单例的写法

    早上随便翻到单例的写法,那我也随手写几个吧 除了以下几种,需要知道枚举也是属于一种实现方式,并且它可以防止序列化/...

  • 如何实现单例,单例的弊端

    单例在项目中是必不可少的,他可以使我们全局共享我们的数据。 首先,单例写法有好几种,通常的写法是基于线程安全的写法...

  • Java设计模式—单例模式

    概念 java中单例模式是一种常见的设计模式,单例模式的写法有好几种,比较常见的有:懒汉式单例、饿汉式单例。单例模...

网友评论

    本文标题:iOS 再谈单例的几种写法

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