zoukankan      html  css  js  c++  java
  • Objective-C的单例实现

     在这些设计模式中,我发现自己最需要用到的是Singleton模式。在程序中,我需要一系列的对象,他们每一个内部都包含有一组变量和功能,是静态的,而且整个程序都只需要拥有一个该类的对象。
        例如:
        1.控制程序执行的命令器
        2.管理数据库
        3.音效控制
        4.文件处理

    单例是在程序声明周期里 有且仅有 被实例化过一次的类。为确保实例化的唯一,利用类的 类(static)方法来生成和访问对象。

    至此,你便可以在程序中任何地方访问类的单例对象,因为只实例化唯一的一次,所以,并不用 alloc、init、autorelease初始化方法。

    Singleton 模式的实现

    在objective-C中,实现Singleton模式,只需实现以下四个步骤:

    1.  为 Singleton Object 实现一个静态实例,并初始化,然后设置成nil;

    2. 实现一个实例构造方法 (通常命名为 sharedInstance 或者 sharedManager) 检查上面声明的静态实例是否为nil,如果是,则新建并返回一个本类实例;

    3. 重写allocWithZone: 方法,用来保证当其他人直接使用 alloc 和init 试图获得一个新实例的时候,不会产生一个新的实例。

    4. 适当地实现  allocWithZone,  copyWithZone,  release 和 autorelease。

    + (id)sharedInstance
    {
      static dispatch_once_t pred = 0;
      __strong static id _sharedObject = nil;
      dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; // or some other init method
      });
      return _sharedObject;
    }
    

    The block given to dispatch_once will, as the name implies, only ever be called once. This will ensure only one instance is created. It's also fast and thread safe: no synchronized or nil checks required.

    We can go one step further and wrap this up in a convenient macro. Now all you need to do is this:

    + (id)sharedInstance
    {
      DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
        return [[self alloc] init];
      });
    }

    参考 http://lukeredpath.co.uk/blog/2011/07/01/a-note-on-objective-c-singletons/

  • 相关阅读:
    机器学习面试问题7
    机器学习面试问题6
    机器学习面试问题5
    机器学习面试问题4
    机器学习面试问题3
    机器学习面试问题2
    机器学习面试问题1
    推荐算法
    机器学习面试问题8
    决策树与随机森林算法
  • 原文地址:https://www.cnblogs.com/codings/p/3567213.html
Copyright © 2011-2022 走看看