zoukankan      html  css  js  c++  java
  • 使用单例时的三种单例写法

    单例:一个类仅仅有一个实例,在外部创建对象时,不能用alloc.(仅仅要alloc,就会在堆区开辟空间,就意味着有多个对象)所以我们要提供一个创建对象的方法:
    1.加号方法

    2.返回值类型为当前类

    3.方法名以default ,standared,main,shared等开头 + 当前类名


    以下以Person类为例

    在.h文件里声明

    + (Person *)sharePerson;


    在.m文件实现
    第一种模式(单线程使用这样的模式)

    + (Person *)sharePerson {   

    声明为static,保证变量在程序执行期间不会回收,并且仅仅保证初始化一次   

    单例的空间在程序的执行期间不回收,要慎重使用,否则会造成内存堆积 

      static Person *person = nil;   

      if (!person) { 

         person = [[Person alloc] init];   

    }   

         return person;

    }


    另外一种模式(多线程使用这样的模式)

    + (Person *)sharePerson {    

    多线程写法   

        static Person *person = nil;   

        @synchronized(self)    {       

        if (person == nil) {           

            person = [[Person alloc] init];       

        }       

    }   

            return person;

    }


    第三种模式(单线程与多线程均可使用这样的模式)

    + (Person *)sharePerson {       

        static Person *person = nil;   

        static dispatch_once_t onceToken;   

          dispatch_once(&onceToken, ^{      

          保证仅仅运行一次,无论是多线程,还是单线程      

           person = [[Person alloc] init];   

             });       

    return person;

      

  • 相关阅读:
    一款纯css3实现的响应式导航
    一款基于TweenMax.js的网页幻灯片
    4款基于jquery的列表图标动画切换特效
    随着鼠标移动的文字阴影
    一款纯css实现的垂直时间线效果
    一款基于jquery的侧边栏导航
    (转) 共享个很棒的vim配置
    [Leetcode] String to Integer (atoi)
    dia无法输入中文?
    [Leetcode] Sum Root to Leaf Numbers
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6761272.html
Copyright © 2011-2022 走看看