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

    单例模式

     

    目录

    • 概述——对单例模式的理解
    • OC上的单例模式
    • 多线程中的单例模式

    线程安全实现一

    线程安全苹果官方实现

    使用GCD实现单例模式(推荐使用)

    • 单例模式的运用

     

    概述——对单例模式的理解 

     

    OC上的单例模式

    @implementation Singleton

    static Singleton *singleton;

    +(id)sharedInstance{

      if(!singleton){

        singleton = [[Singleton alloc] init];

      }

      return singleton;

    }

    @end

     

    多线程中的单例模式

    线程安全实现一

    +(id)sharedInstance{

      @synchronized(self){

      if(!singleton){

        singleton = [[Singleton alloc] init]; 

      }

      }

      return singleton;

    }

    线程安全苹果官方实现

    +(id)sharedInstance{

      @synchronized(self){

      if(singleton == nil){

        [[self alloc] init];  //assignment not done here

      }

      }

    }

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

      @synchronized(self){

        if(singleton == nil){

          singleton == [super allocWithZone:zone];

          return singleton;  //assignment and return on first allocation

        }

      }

      return nil;  //on subsequent allocation attempts return nil

    }

    -(id)copyWithZone:(NSZone *)zone{

      return self;

    }

    -(id)retain{

      return self;

    }

    -(unsigned)retainCount{

      return UINT_MAX;  //denotes an object that cannot be released

    }

     -(void)release{

    }

    -(id)autorelease{

      return self;

    }

    注释

    使用@synchronized( )指令可以锁住在线程中执行的某一个代码块

    @synchronized()指令的唯一参数可以使用任何OC对象,包括self。这个对象就是我们所谓的信号量

    最安全的是,在应用程序进入多线程之前,为所有需要互斥的创建互斥信号量

    使用GCD实现单例模式(推荐使用)

    + (IQKeyboardManager*)sharedManager

    {

    //Singleton instance

    static IQKeyboardManager *kbManager;

    //Dispatching it once.

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{ 

    //  Initializing keyboard manger.

            kbManager = [[self alloc] init];

    });

    //Returning kbManager.

    return kbManager;

    }

    -(id)init

    {

    if (self = [super init])

        { 

            static dispatch_once_t onceToken;

            dispatch_once(&onceToken, ^{

        }

      }

    }

     

    单例模式的运用

     

  • 相关阅读:
    scm工作流部署问题解决
    mysql 数据库时间慢了8小时
    Vue加了二级路由后,跳转后js好像都失效
    flutter 莫名其妙错误集锦
    confluence-6.7.1 install
    git idea 项目复原
    springboot 本地jar发布,打war包
    flutter 初探2--点击按钮打开新窗口
    [转载]无法解决 equal to 操作中 "Chinese_PRC_CI_AS" 和 "Chinese_PRC_CI_AS_KS_WS" 之间的排序规则冲突
    [转载]天赋秉异的人永远是少数
  • 原文地址:https://www.cnblogs.com/IOS-Developer/p/4183911.html
Copyright © 2011-2022 走看看