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

    单例模式需要达到的目的

    1. 封装一个共享的资源

    2. 提供一个固定的实例创建方法

    3. 提供一个标准的实例访问接口

     

    在iOS中有很多单例对象,比如UIApplication,UIScreen等等。

    //.h文件
    #import <Foundation/Foundation.h>
    @interface Singleton : NSObject
    //单例方法
    +(instancetype)sharedSingleton;
    @end
    //.m文件
    #import "Singleton.h"
    @implementation Singleton
    //全局变量
    static id _instance = nil;
    //单例方法
    +(instancetype)sharedSingleton{
        return [[self alloc] init];
    }
    ////alloc会调用allocWithZone:
    +(instancetype)allocWithZone:(struct _NSZone *)zone{
        //只进行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    //初始化方法
    - (instancetype)init{
        // 只进行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super init];
        });
        return _instance;
    }
    //copy在底层 会调用copyWithZone:
    - (id)copyWithZone:(NSZone *)zone{
        return  _instance;
    }
    + (id)copyWithZone:(struct _NSZone *)zone{
        return  _instance;
    }
    + (id)mutableCopyWithZone:(struct _NSZone *)zone{
        return _instance;
    }
    - (id)mutableCopyWithZone:(NSZone *)zone{
        return _instance;
    }
    @end

    单例模式使用

    [plain 

    [[SingletonClass sharedInstance] xxx];  

     

    单例的销毁

    销毁也就是对单例的释放,在应用终止的时候实现,delegate方法如下。

     

    [plain]  

    - (void)applicationWillTerminate:(UIApplication *)application  

    {  

        [SingletonClass destroyDealloc];  

    }  

     

     

    销毁方法

    [plain]  

    + (void)destroyDealloc  

    {  

        if ([getInstance retainCount] != 1)  

            return;  

          

        [getInstance release];  

        getInstance = nil;  

    }  

     




    (重点)另外一种单例的创建:http://blog.csdn.net/lovefqing/article/details/8516536


  • 相关阅读:
    未处理的异常 stack overflow
    Largest Rectangle in a Histogram [POJ2559] [单调栈]
    Blocks [POJ3734] [矩阵快速幂]
    Rectangular Covering [POJ2836] [状压DP]
    Arrange the Bulls [POJ2441] [状压DP]
    The Water Bowls [POJ3185] [开关问题]
    Bound Found [POJ2566] [尺取法]
    4 Values whose Sum is 0 [POJ2785] [折半搜索]
    Physics Experiment 弹性碰撞 [POJ3684]
    Fliptile [POJ3279] [开关问题]
  • 原文地址:https://www.cnblogs.com/meixian/p/6086995.html
Copyright © 2011-2022 走看看