美文网首页
单例设计模式

单例设计模式

作者: IreneWu | 来源:发表于2017-12-30 11:04 被阅读21次

1.单例设计模式(Singleton)
1> 什么: 它可以保证某个类创建出来的对象永远只有1个

2> 作用(为什么要用)

  • 节省内存开销
  • 如果有一些数据, 整个程序中都用得上, 只需要使用同一份资源(保证大家访问的数据是相同的,一致的)
  • 一般来说, 工具类设计为单例模式比较合适

3> 怎么实现

  • MRC(非ARC)
//static保证全局变量不让别人访问
static MJSoundTool *_soundTool = nil;

/**
 *  alloc方法内部会调用allocWithZone:
 *  zone : 系统分配给app的内存
 */
+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_soundTool == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ // 安全(这个代码只会被调用一次)
            _soundTool = [super allocWithZone:zone];
        });
    }
    return _soundTool;
}

- (id)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _soundTool = [super init];
    });
    return _soundTool;
}

+ (instancetype)sharedSoundTool
{
    return [[self alloc] init];
}

- (oneway void)release
{

}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return 1;
}

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

  • ARC
static id _instance = nil;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_instance == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ // 安全(这个代码只会被调用一次)
            _instance = [super allocWithZone:zone];
        });
    }
    return _instance;
}

- (id)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super init];
    });
    return _instance;
}

+ (instancetype)sharedSoundTool
{
    return [[self alloc] init];
}

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

相关文章

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式第二篇、单例设计模式

    目录1、什么是单例设计模式2、单例设计模式的简单实现3、单例设计模式面临的两个问题及其完整实现4、单例设计模式的应...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 2、创建型设计模式-单例设计模式

    江湖传言里的设计模式-单例设计模式 简介:什么是单例设计模式和应用 备注:面试重点考查 单例设计模式:这个是最简单...

  • 设计模式之单例模式

    单例设计模式全解析 在学习设计模式时,单例设计模式应该是学习的第一个设计模式,单例设计模式也是“公认”最简单的设计...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

网友评论

      本文标题:单例设计模式

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