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; 
    }
  • 相关阅读:
    HDU 4069 Squiggly Sudoku
    SPOJ 1771 Yet Another NQueen Problem
    POJ 3469 Dual Core CPU
    CF 118E Bertown roads
    URAL 1664 Pipeline Transportation
    POJ 3076 Sudoku
    UVA 10330 Power Transmission
    HDU 1426 Sudoku Killer
    POJ 3074 Sudoku
    HDU 3315 My Brute
  • 原文地址:https://www.cnblogs.com/samyangldora/p/4631511.html
Copyright © 2011-2022 走看看