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
    
  • 相关阅读:
    修改 MyEclipse 中的 jsp 和 servlet 模板
    javaWeb 数据库连接池连接数据库
    发现一个类的方法不够用时,可以使用的3种方法可以增强
    使用 greenDao 框架 操作数据库
    Android之使用Volley框架在ListView中加载大量图片
    js日期选择控件
    mysql 乱码问题
    java 使用反射技术解耦
    javaWeb 使用jsp开发 html过滤标签
    javaWeb 使用jsp开发 foreach 标签
  • 原文地址:https://www.cnblogs.com/ShaRuru/p/5046549.html
Copyright © 2011-2022 走看看