iOS单例模式

作者: 搬运工开发者 | 来源:发表于2016-12-16 15:04 被阅读221次

今天去面试,对方公司给的试卷中有一道题是写单例模式,面试的时候也问了我单例模式的优缺点。老实说回答得相当不好,对方也指出了我代码中的不严谨。回来自己从新查找了一下资料,重新总结了一下。
主要优点:
1、提供了对唯一实例的受控访问。
2、由于在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。
3、允许可变数目的实例。

主要缺点:
1、由于单利模式中没有抽象层,因此单例类的扩展有很大的困难。
2、单例类的职责过重,在一定程度上违背了“单一职责原则”。
3、滥用单例将带来一些负面问题,如为了节省资源将数据库连接池对象设计为的单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出;如果实例化的对象长时间不被利用,系统会认为是垃圾而被回收,这将导致对象状态的丢失.

以下是相对严谨的做法

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCopying, NSMutableCopying>
+ (instancetype)sharePerson;
@end
#import "Person.h"

//全局
static Person *_person;

@implementation Person

//初始化方法
- (instancetype)init{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [super init];
    });
    return _person;
}

//单例方法
+ (instancetype)sharePerson{
    return [[self alloc] init];
}

//alloc会调用allocWithZone,确保使用同一块内存地址
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [super allocWithZone:zone];
    });
    return _person;
}

//copy的时候会调用copyWithZone
- (id)copyWithZone:(NSZone *)zone{
    return _person;
}

+ (id)copyWithZone:(struct _NSZone *)zone{
    return _person;
}

+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
    return _person;
}

- (id)mutableCopyWithZone:(NSZone *)zone{
    return _person;
}
Person *person1 = [[Person alloc]init];
    Person *person2 = [Person sharePerson];
    Person *person3 = [[Person alloc]init];
    Person *person4 = [person3 mutableCopy];
    Person *person5 = [person4 copy];
    NSLog(@"%p %p %p %p %p", person1, person2, person3, person4, person5);
// 0x170001ad0 0x170001ad0 0x170001ad0 0x170001ad0 0x170001ad0

相关文章

  • 单例

    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/atzwmttx.html