zoukankan      html  css  js  c++  java
  • OC中单例的各种写法及基本讲解

    1、典型的单例写法

    1 static id sharedMyManager;
    2 +(id)shareThemeManager{
    3     if(sharedThemeManager == nil){
    4              shareMyManager = [[self alloc]init];
    5     }
    6   return sharedMyManager;
    7 }

    缺点:无法保证多线程情况下只创建一个对象。适用于只有单线程。

    2、加锁的写法:

     1 static sharedManager* single = nil;
     2 
     3 +(sharedManage*)sharedManage{
     4 
     5     @synchronized(self){   //加锁,保证多线程下也只能有一个线程进入
     6 
     7         if (!single) {
     8 
     9             single = [[self alloc]init];
    10 
    11         }
    12 
    13     }
    14 
    15     return single;
    16 
    17 }

    这种方法较常用。

    3、GCD写法:

    static sharedManager * single = nil;
    +(id)sharedManager{
    
         static dispatch_once_t once;
    
          dispatch_once(&once,^{
                   single = [[self alloc]init];
    });

    return single;
    }

    4、免锁(Lock free)的写法:

     1 static sharedManager * single = nil;
     2 
     3     +(void)initialize{
     4  
     5      static BOOL initialized = NO;
     6  
     7      if (initialized == NO){
     8  
     9          initialized = YES;
    10  
    11          shareMyManager = [[self alloc]init];
    12 
    13           }
    14  
    15  }

    单例全面的写法:

    重载以下方法:

    +(id)allocWithZone:(NSZone *)zone;

    +(id)copyWithZone:(NSzone *)zone;

    +(id)retain;

    +(void)release; //单例里面重写单例不允许release,autorrelease,所以重写

    +(void)autorelease;

  • 相关阅读:
    MySql中引擎
    Session和Cookie的区别和联系
    Global Round 2
    CF550 DIV3
    Java的反射机制
    IO多路复用
    简单DP内容
    Java 对象的创建以及类加载
    Java 一些常见问题(持续更新)
    红黑树的一些知识点
  • 原文地址:https://www.cnblogs.com/shaoting/p/4889872.html
Copyright © 2011-2022 走看看