zoukankan      html  css  js  c++  java
  • 关于单例设计模式

    在ios开发中,很多时候我们会需要用到单例,一般我们会用到两种实现单例的方式。第一种是:

    第二种是:

    针对这两个方法,我们提出两点疑问:

    1.为什么必须用static修饰符?

    2.这两种方法有什么区别?

    我们先来回答第一个问题。static修饰符在这里的作用就是把变量分配在静态存储区,并且只会分配一次内存,无论你调用多少次这个方法,被static修饰的变量就是它第一次分配的那个,它的生命周期是从应用程序开始到应用程序结束。这样就保证了这个单例对象的唯一性。如果我们不用static修饰符,那么每次调用这个单例方法的时候,系统每次都会在栈上分配一个变量,这样生成的实例就不唯一了。

    这两种生成单例的方法的区别是方法一不是线程安全的,在多线程的环境下可能有多个线程同时调用了方法一,造成生成不同的实例,而方法二是线程安全的,这附上苹果官方文档的解释:

    dispatch_once


    Executes a block object once and only once for the lifetime of an application.

    Declaration


    void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);


    Parameters

    predicate:A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.


    block:The block object to execute once.

    This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.If called simultaneously from multiple threads, this function waits synchronously until the block has completed.The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

  • 相关阅读:
    文件操作
    join,列表和字典用for循环的删除,集合,深浅拷贝
    java多线程基础
    nginx应用及性能调优
    nginx 基本功能
    SpringBoot2.x 启动过程详解
    shell脚本的基本使用
    使用 maven 的 `wagon-maven-plugin`插件 快速部署 到不同的 环境
    Netty笔记(7)
    Netty笔记(6)
  • 原文地址:https://www.cnblogs.com/qmmq/p/5279567.html
Copyright © 2011-2022 走看看