美文网首页
单例的实现方式

单例的实现方式

作者: 通哥 | 来源:发表于2018-10-09 16:38 被阅读0次

第一种: GCD实现 (推荐使用)

新建一个Person类,在.h文件中添加方法

@interface Person : NSObject
+(instancetype)sharePerson;
@end

在.m文件中添加方法

#import "Person.h"
@interface Person()
@end
@implementation Person

static Person *_person;

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

+ (instancetype)sharePerson{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [[super alloc] init];
    });
    return _person;
}

- (id)copyWithZone:(NSZone *)zone{
    return _person;
}
@end

第二种: 通过重写类方法实现

新建一个Person类,在.h文件中添加方法

@interface Person : NSObject

+ (instancetype)sharePerson;

@end

在.m文件中添加方法

#import "Person.h"

@implementation Person
static Person *_person;

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    @synchronized (self) {
        if (_person == nil) {
            _person = [super allocWithZone:zone];
        }
    };
    return _person;
}

+ (instancetype)sharePerson{
    @synchronized (self) {
        if (_person == nil) {
            _person = [[super alloc] init];
        }
    }
    return _person;
}

- (id)copyWithZone:(NSZone *)zone{
    return _person;
}
@end

注:

  1. 在第二种创建单例中, 必须对重写方法进行加锁, 因为考虑到线程安全问题,如果不加锁, 可能两个线程同时访问, 就会出现分配两个内存空间的情况..
  2. 单例的实现不能使用继承, 这样会造成所有继承的单例都是同一个对象

相关文章

  • iOS 单例模式 - 单例对象销毁【@synchronized】

    单例对象的创建方式 单例.h 文件的实现 单例.m 文件的实现 单例对象的销毁【@synchronized创建方式...

  • iOS 单例模式 - 单例对象销毁【GCD】

    单例对象的创建方式 单例.h 文件的实现 单例的.m 文件的实现 单例对象的销毁【GCD创建的方式】 使用单例对象...

  • 单例模式的常用实现方式

    单例模式属于最常用的设计模式,Java中有很多实现单例模式的方式,各有其优缺点 实现方式对比 单例实现方式线程安全...

  • 单例模式(Singleton)- 通俗易懂的设计模式解析

    单例模式的实现方式单例模式的实现方式有多种,根据需求场景,可分为2大类、6种实现方式。具体如下: a. 初始化单例...

  • Python经典面试题21道

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python最经典面试题21道,必看!

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • 设计模式--单例模式

    单例模式概述 单例模式实现方式 为什么要使用单例模式 单例模式实现方式 饿汉式 类加载后就会将对象加载到内存中,保...

  • 完美的单例

    一、常见的单例实现方式 方式一(静态常量) 方式二(内部类) 方式三(懒加载) 二、常见单例实现方式的问题 方式一...

网友评论

      本文标题:单例的实现方式

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