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
    
  • 相关阅读:
    1442. Count Triplets That Can Form Two Arrays of Equal XOR
    1441. Build an Array With Stack Operations
    312. Burst Balloons
    367. Valid Perfect Square
    307. Range Sum Query
    1232. Check If It Is a Straight Line
    993. Cousins in Binary Tree
    1436. Destination City
    476. Number Complement
    383. Ransom Note
  • 原文地址:https://www.cnblogs.com/ShaRuru/p/5046549.html
Copyright © 2011-2022 走看看