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

      - 在IOS中有一个很重要的设计模式,那就是单例模式。何为单例模式呢?那就是至始至终它的内存地址都是只有一份。

      - 单例模式的作用

        - 可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问
        - 从而方便地控制了实例个数,并节约系统资源
     
      - 单例模式的使用场合
      - 在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

    实现

      - 普通方式:

    static id _instance;
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        // 加入同步锁,防止多线程的情况下,同时进入创建实例
        @synchronized(self){
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
            return _instance;
        }
    }
    
    + (instancetype)sharedIntance
    {
        @synchronized(self){
            if (_instance == nil) {
                _instance = [[self alloc] init];
            }
        }
        return _instance;
    }
    
    - (id)copyWithZone:(NSZone *)zone
    {
        return _instance;
    }

      - GCD形式创建

    static id _instance;
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    
    + (instancetype)sharedInstance
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[self alloc] init];
        });
        return _instance;
    }
    
    - (id)copyWithZone:(NSZone *)zone
    {
        return _instance;
    }

      - 利用宏的形式创建,方便以后直接调用 

    // .h文件
    #define  SAMSingletonH(name)  + (instancetype)shared##name;
    
    // .m文件
    #define  SAMSingletonM(name)  
    
    static id _instance; 
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone 
    { 
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{  
            _instance = [super allocWithZone:zone]; 
        }); 
        return _instance; 
    } 
      
    + (instancetype)shared##name  
    {  
        static dispatch_once_t onceToken; 
        dispatch_once(&onceToken, ^{  
            _instance = [[self alloc] init]; 
        }); 
        return _instance; 
    } 
     
    - (id)copyWithZone:(NSZone *)zone 
    { 
        return _instance; 
    }
  • 相关阅读:
    DFS——CodeForces740DAlyona and a tree
    DFS——hdu1016Prime Ring Problem
    DFS(8)——poj2034Anti-prime Sequences
    DFS(7)——poj1011Sticks
    DFS(2)——hdu1241Oil Deposits
    DFS(6)——hdu1342Lotto
    NO12——快速幂取模
    NO11——01背包
    NO10——各种欧几里得
    NO9——线段相关
  • 原文地址:https://www.cnblogs.com/samyangldora/p/4631511.html
Copyright © 2011-2022 走看看