zoukankan      html  css  js  c++  java
  • 一句话实现OC单例模式

    首先新建一个头文件,定义如下宏:

    // .h文件的实现
    #define SingletonH(methodName) + (instancetype)shared##methodName;
    
    // .m文件的实现
    #if __has_feature(objc_arc) // 是ARC
    #define SingletonM(methodName) 
    static id _instace = nil; 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
    if (_instace == nil) { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super allocWithZone:zone]; 
    }); 
    } 
    return _instace; 
    } 
    
    - (id)init 
    { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super init]; 
    }); 
    return _instace; 
    } 
    
    + (instancetype)shared##methodName 
    { 
    return [[self alloc] init]; 
    } 
    + (id)copyWithZone:(struct _NSZone *)zone 
    { 
    return _instace; 
    } 
    
    + (id)mutableCopyWithZone:(struct _NSZone *)zone 
    { 
    return _instace; 
    }
    
    #else // 不是ARC
    
    #define SingletonM(methodName) 
    static id _instace = nil; 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
    if (_instace == nil) { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super allocWithZone:zone]; 
    }); 
    } 
    return _instace; 
    } 
    
    - (id)init 
    { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super init]; 
    }); 
    return _instace; 
    } 
    
    + (instancetype)shared##methodName 
    { 
    return [[self alloc] init]; 
    } 
    
    - (oneway void)release 
    { 
    
    } 
    
    - (id)retain 
    { 
    return self; 
    } 
    
    - (NSUInteger)retainCount 
    { 
    return 1; 
    } 
    + (id)copyWithZone:(struct _NSZone *)zone 
    { 
        return _instace; 
    } 
     
    + (id)mutableCopyWithZone:(struct _NSZone *)zone 
    { 
        return _instace; 
    }
    
    #endif
    

    然后在你定义单例类的

    .h 文件 写 SingletonH(MyMethodName) 

    .m 文件写 SingletonM(MyMethodName)

    搞定!

  • 相关阅读:
    23种设计模式之单例模式
    6大设计原则之里氏替换原则
    6大设计原则之依赖倒置原则
    6大设计原则之接口隔离原则
    6大设计原则之迪米特法则
    Java日志第14天 2020.7.19
    Java日志第15天 2020.7.20
    Java日志第13天 2020.7.18
    Python 语音识别字幕生成器
    python list,tuple,str有序问题
  • 原文地址:https://www.cnblogs.com/hoyawolfer/p/4638114.html
Copyright © 2011-2022 走看看