美文网首页
单例模式

单例模式

作者: jadyn_JT | 来源:发表于2016-04-04 14:12 被阅读23次

1)第一种方法

//当程序销毁时,静态变量也销毁,
static YuTian *yutian = nil;

+(YuTian *)shareInstance{
    if (yutian == nil) {
     yutian = [[YuTian alloc] init];
    }
    return yutian;
}

//为了防止 开发者 通过 alloc new来构建新对象,需要重写allocWithZone方法
+(id)allocWithZone:(NSZone *)zone{
    if (yutian == nil) {
        yutian = [[super allocWithZone:zone] init];
    }
    return yutian;
}

//为了防止通过copy产生新的实例对象,需要重写copy方法
-(id)copyWithZone:(NSZone *)zone{
    return self;
}

//## 以下代码仅在非ARC环境下使用 ##
#if !__has_feature(objc_arc)

-(id)retain{
 return self;
}

-(unsigned long)retainCount{
 return NSIntegerMax;
}

-(void)release{
  //空代码
}

-(void)autorelease{
  return self;
}

#endif

2)第二种方法(使用 GCD 的方式 创建单例)

//当程序销毁时,静态变量也销毁,
static City *city = nil;

//使用 GCD 的方式 创建单例
+(instancetype)shareInstance{

    //防止本方法被多次调用而引发冲突
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
      //此处的代码仅会被调用一次
        city = [self new];
    
    });
    return city;  
}

//如果允许另外使用alloc/new创建 非单例对象,则不必重写此方法
+(instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken,^{
    
        city = [super allocWithZone:zone];
    
    });    
    return city;
}

相关文章

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

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

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

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

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

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

  • java的单例模式

    饿汉单例模式 懒汉单例模式

网友评论

      本文标题:单例模式

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