zoukankan      html  css  js  c++  java
  • 2016.01.22 单例模式(Singleton)

    单例模式:整个程序的一个类只能有一个实例对象:(UIApplication、NSUserDefaults等都是IOS中的系统单例)

            1.物理设备  eg:打印机

            2.不可多个同时存在的资源  eg:数据库

    单例的写法:

      这是第一种,也是最简单、最常用的一种:

     1 #import "FileOpration.h"
     2 
     3 static FileOpration *instance = nil;        //静态变量,从定义开始到整个程序结束
     4 
     5  @implementation FileOpration 
     6 
     7 + (instancetype)sharedFileOpration{
     8 
     9     if (instance == nil) {
    10         instance = [[FileOpration alloc]init];
    11     }
    12 
    13     return instance;
    14 } 
    15 
    16 @end

      第二种写法,加入了线程,以及重写alloc方法

    + (FileOperation *)sharedManager{  
            static FileOperation *instance = nil;  
            static dispatch_once_t predicate;  
            dispatch_once(&predicate, ^{  
                    instance = [[self alloc] init];   
            });  
        return ManagerInstance;  
    }
    
    /*
      重写alloc方法,在调用alloc方法的时候实际上是默认调用allocWithZone
      */
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        return [self sharedOperation];
    }
  • 相关阅读:
    控件视图的实现原理
    建造者模式
    leetcode701
    leetcode991
    leetcode990
    leetcode989
    leetcode988
    leetcode987
    leetcode986
    leetcode985
  • 原文地址:https://www.cnblogs.com/immustard/p/5158233.html
Copyright © 2011-2022 走看看