美文网首页
设计模式 -- 单例模式

设计模式 -- 单例模式

作者: user_bo | 来源:发表于2019-02-26 14:45 被阅读0次

1.单例模式

在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的一个类只有一个实例。

即一个类只有一个对象实例。

2.使用单例原因:

ios 程序(oc swift)的编程习惯。

xcode 版本 4.2 之前,手动内存管理,容易发生内存泄露,单例不用考虑这个问题。(不需要每次 alloc release操作)

xcode 版本 4.2 之后,自动内存管理,当对象大量生产,容易内存溢出,单例具有全局唯一性,只有一个实例,使用了最少的内存,避免了内存溢出问题;

3.单例优势

1.单例全局唯一,只有一个实例
2.节约内存,调用,不用多次开辟空间
3.信息共享: 因为实例是唯一的,所以属性,属性值可以共享

4.简单单例的创建(线程安全的)

#import "UserCenter.h"

static UserCenter *_mySingle = nil;

+ (instancetype)managerCenter{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mySingle = [[UserCenter alloc] init];
    });
    return _mySingle;    
}

5.单例的创建(内存安全)

#import "UserCenter.h"

static UserCenter *_mySingle = nil;
+(instancetype)shareInstance
{
    if (_mySingle == nil) {
        _mySingle = [[UserCenter alloc] init];
    }
    return _mySingle;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mySingle = [super allocWithZone:zone];
    });
    return _mySingle;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    return self;
}

6. vc 客户端调用

// 构建方法创建
    UserCenter * center = [UserCenter managerCenter];
    center.name = @"users";
    center.age = 18;
    
// 系统方法 创建 复写了 allocwithZone 方法,所以安全
    UserCenter * new = [[UserCenter alloc]init];
    
    NSLog(@"UserCenter :name: %@,age: %d",new.name,new.age);

7.单例模式UML

单例模式.png

相关文章

  • 单例模式Java篇

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

  • python中OOP的单例

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

  • 单例

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

  • 设计模式 - 单例模式

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

  • 设计模式

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

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

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

  • python 单例

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

  • 基础设计模式:单例模式+工厂模式+注册树模式

    基础设计模式:单例模式+工厂模式+注册树模式 单例模式: 通过提供自身共享实例的访问,单例设计模式用于限制特定对象...

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

  • 设计模式之单例模式

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

网友评论

      本文标题:设计模式 -- 单例模式

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