zoukankan      html  css  js  c++  java
  • 实现单例模式

    单例模式

    • 单例是设计模式中十分常见的一种,在iOS开发中也会经常用到。
    • 当有多处代码块需要使用同一个对象实例时,单例模式可以保证在程序运行过程,一个类只有一个实例(而且该实例易于供外界访),从而方便地控制了实例个数,节约系统资源

    单例的实现

    • 类的alloc方法内部其实调用了allocWithZone:方法。创建一个该类的静态实例,重写此方法,访问时为若静态实例为nil,则调用super allocWithZoen:返回实例
    • 倘若发生多线程同时访问,可能会创建多份实例,因此需要加锁@synchronized或GCD的一次性代码(常用)控制实现只创建一份
    • 为符合代码规范,一般在实现单例模式时,会给这个类提供类方法方便外界访问,方法名用default | shared开头以表明身份(这样其他人调用时,一看方法名就知道是单例类了)
    • 完善起见,还要重写copyWithZonemutableCopyWithZone:方法(需要先遵守NSCopyingNSMutableCopying协议)
    @implementation Tool
    static Tool *_instance = nil;
    +(instancetype)allocWithZone:(struct _NSZone *)zone{
        /*
        @synchronized(self) {
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
        }
        return _instance;
         */
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
        });
        return _instance;
    }
    +(instancetype)sharedTool{
        return [[self alloc] init];
    }
    -(id)copyWithZone:(NSZone *)zone{
        return _instance;
    }
    -(id)mutableCopyWithZone:(NSZone *)zone{
        return _instance;
    }
    @end
    
  • 相关阅读:
    Consul 学习文章链接
    秒懂:tomcat 最大线程数 最大连接数
    使用 Spring Cloud Sleuth 实现链路监控 (转)
    (转)Java中OutOfMemoryError(内存溢出)的三种情况及解决办法
    @RequestMapping 用法
    Spring 常用的几种注解
    [转] Spring MVC 深入分析
    [转]session listener的配置和使用
    web.xml中 Log4jConfigListener配置
    [mysql] 手动备份数据
  • 原文地址:https://www.cnblogs.com/ShaRuru/p/5046549.html
Copyright © 2011-2022 走看看