单例模式

一、简介

      简单说来,单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个(当然也可以不存在)

当你使用alloc之类的再次新建一个类的时候,编译器不会报错,但是也不会新建一个类。

二、IOS实现单例的方式

      IOS中,一般单例的获取方式都是带有share的,例如:UIApplication *app = [UIApplication  shareApplication]
       
     1、一般我们常用的alloc方法是包含了内存分配和初始化两个步骤,alloc 函数在总是会先调用allocWithZone进行内存分配 ,所以在定义单例    
          的时候,必须从内存分配上确保是只分配一次,所以根源上是从写allocWithZone方法,只执行一次即可。避免有人直接调allocWithZone 
          方法导致单例错误
 
   2、在多线程的时候,也有可能出现错误,GCD中的方法,dispatch_once_t ,是多线程安全的,在整个生命周期值执行一次
 
     1、普通的方式,多线程不安全,需要加锁,才能多线程安全
      static MyGizmoClass *sharedGizmoManager = nil;
      + (MyGizmoClass*)sharedManager
        {
             if (sharedGizmoManager == nil)
              {
                 sharedGizmoManager = [[super allocWithZone:NULL] init];
              }
              return sharedGizmoManager;
       }
 
 
      + (id)allocWithZone:(NSZone *)zone
       {
              return [[self sharedManager] retain];
       }
 
 
      2、多线程安全方式
           static class *_instance;
           + (id)allocWithZone:(struct _NSZone *)zone 
          { 
                 static dispatch_once_t onceToken; 
                 dispatch_once(&onceToken, ^{ 
                         _instance = [super allocWithZone:zone]; 
                 }); 
 
                 return _instance; 
           } 
 
           + (instancetype)sharedStudent 
           { 
                   if (_instance == nil) { 
                            _instance = [[class alloc] init]; 
                    } 
 
                    return _instance; 
           }
 
   
        3、推荐方式,可移植性高(class   需要单例的类名)
           // .h 文件中调用
          #define singleton_interface(class) + (instancetype)shared##class;
          // .m 文件中调用
          #define singleton_implementation(class)
          
           static class *_instance;
           + (id)allocWithZone:(struct _NSZone *)zone 
          { 
                 static dispatch_once_t onceToken; 
                 dispatch_once(&onceToken, ^{ 
                         _instance = [super allocWithZone:zone]; 
                 }); 
 
                 return _instance; 
           } 
 
           + (instancetype)shared##class 
           { 
                   if (_instance == nil) { 
                            _instance = [[class alloc] init]; 
                    } 
 
                    return _instance; 
           }
   
原文地址:https://www.cnblogs.com/hepingqingfeng/p/5462701.html