zoukankan      html  css  js  c++  java
  • iOS

    SingletonPattern

    取经的地址这里

    1.单例模式作用和缺点####

    • 共享资源
    • 管理中心
    • 缺点:增加耦合

    2.严格单例的要求####

    • 严格的单例模式是无法通过alloc init 方法来生成单例对象的。
    • 不能派生子类,即使派生子类,子类也无法创建单例对象。
    • 防止单例对象被释放。

    3.单例模式的应用要求####

    • 单例模式接口要隐藏实现细节。
    • 使用单例模式需要对其进行上层的封装。

    4.严格代码实现####

    下载代码

    
    #import "Singleton.h"
    
    /*
       值得说明的是static关键词的作用,static修饰的变量是在程序运行开始就保存在内存的静态区中,静态区中还有的就是全局变量。这也是单例为什么能够实现共享数据的关键。
    */
    static Singleton * _shareSingleton = nil;
    
    @implementation Singleton
    
    //*> 不允许使用init创建单例对象
    - (instancetype)init
    {
        [NSException raise:@"SingletonPattern"
                    format:@"Cannot instance singleton using 'init' method, shareInstance must be used."];
        
        return nil;
    }
    
    //*> 不允许使用copy创建单例对象
    - (id)copyWithZone:(NSZone *)zone
    {
        [NSException raise:@"SingletonPattern"
                    format:@"Cannot instance singleton using copy method, shareInstance must be used."];
        
        return nil;
    }
    
    + (Singleton *)shareInstance
    {
        if (self != [Singleton class])
        {
            [NSException raise:@"SingletonPattern"
                        format:@"Cannot use shareInstance method from subclass."];
        }
    
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _shareSingleton = [[Singleton alloc] initInstance];
        });
        
        return _shareSingleton;
    }
    
    - (id)initInstance
    {
        return [super init];
    }
    
    @end
    
    

    5.单例应用代码示范###

    首先一定要满足,单例在应用中的几点规范。

    测试代码

  • 相关阅读:
    linux使用rm-rf删除之文件恢复
    性能测试常见瓶颈分析及调优方法
    性能压测QPS 和 TPS区别
    Linux查看系统性能
    Python中split()和split(" ")的区别
    Python-标准库之functools
    Python-内置函数_@propery、@classmethod、@staticmethod详解
    Python-类的内置方法中__repr__和__str__的区别
    Python-标准库之运算符替代函数Operator
    Python-标准库之迭代器-itertools
  • 原文地址:https://www.cnblogs.com/R0SS/p/5358420.html
Copyright © 2011-2022 走看看