• iOS设计模式之单例模式


    单例模式是iOS常用设计模式中的一种。单例设计模式的作用是使得这个类的一个对象成为系统中的唯一实例,因此需要用一种唯一的方法去创建这个对象并返回这个对象的地址。那么,我们何时使用单例模式呢?1、类只能有一个实例,而且必须从一个为人熟知的访问点对其访问。2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。

    那么用Objective-C如何实现单例模式呢?下面我们来新建一个Singleton类,在Singleton.h中实现如下

    1. @interface Singleton : NSObject  
    2.   
    3. + (Singleton *) sharedInstance;  
    4.   
    5. @end  

    在Singleton.m

    1. @implementation Singleton  
    2.   
    3. static Singleton * sharedSingleton = nil;  
    4.   
    5. + (Singleton *) sharedInstance  
    6. {  
    7.     if (sharedSingleton == nil) {  
    8.         sharedSingleton = [[Singleton alloc] init];  
    9.     }  
    10.     return sharedSingleton;  
    11. }  
    12.   
    13. @end  


    这样就创建一个简单的单例模式,实际上有一部分程序员也是这样实现的,但实际上这是一个不“严格”版本,在实际中使用,可能会遇到发起调用的对象不能以其他分配方式实例化单例对象,否则,就会创建多个实例。(之前有人和我讨论过这个问题,说使用者应该严格按照接口来使用,当实际上Singleton是一个对象,我们不能保证使用者不会使用其他的方法去创建(比如alloc),这个时候他就会创建多个实例,这样就会出现这些无法感知的bug)

    下面我对Singleton.m的进行改进

    1. @implementation Singleton  
    2.   
    3. static Singleton * sharedSingleton = nil;  
    4.   
    5. + (Singleton *) sharedInstance  
    6. {  
    7.     if (sharedSingleton == nil) {  
    8.         sharedSingleton = [[super allocWithZone:NULL] init];  
    9.     }  
    10.     return sharedSingleton;  
    11. }  
    12.   
    13. + (id) allocWithZone:(struct _NSZone *)zone  
    14. {  
    15.     return [[self sharedInstance] retain];  
    16. }  
    17.   
    18. - (id) copyWithZone:(NSZone *) zone  
    19. {  
    20.     return self;  
    21. }  
    22.   
    23. - (id) retain  
    24. {  
    25.     return self;  
    26. }  
    27.   
    28. - (NSUInteger) retainCount  
    29. {  
    30.     return NSUIntegerMax;  
    31. }  
    32.   
    33.   
    34. - (void) release  
    35. {  
    36.     //  
    37. }  
    38.   
    39. - (id) autorelease  
    40. {  
    41.     return self;  
    42. }  
    43.   
    44. @end  


    也许你注意到了,我重载了allocWithZone:,保持了从sharedInstance方法返回的单例对象,使用者哪怕使用alloc时也会返回唯一的实例(alloc方法中会先调用allocWithZone:创建对象)。而retain等内存管理的函数也被重载了,这样做让我们有了把Singleton类变得“严格”了。

  • 相关阅读:
    asp.net core 操作误区
    asp.net core 通过ajax上传图片及wangEditor图片上传
    asp.net core 通过ajax调用后台方法(非api)
    使用 IIS 在 Windows 上托管 ASP.NET Core
    asp.net core 2.0 api ajax跨域问题
    【数据结构】算法 层数最深叶子节点的和 Deepest Leaves Sum
    【数据结构】算法 首个公共祖先 First Common Ancestor
    【数据结构】算法 Top K Frequent Words 前K个高频单词
    【数据结构】算法 Kth Largest Element in an Array 数组中的第K个最大元素
    【数据结构】算法 搜索旋转排序数组 Search in Rotated Sorted Array II
  • 原文地址:https://www.cnblogs.com/Sucri/p/4603784.html
Copyright © 2020-2023  润新知