iOS开发——单例的实现、使用与架构

版权声明:本文为博主原创文章,欢迎转载,转载请标明出处。 http://blog.csdn.net/chenyufeng1991/article/details/50396987

     单例在我们开发中是最常用的设计模式,在iOS中也是如此。单例可以保证某个类的实例在程序中是唯一的,便于进行资源和数据的共享。使用的设计原则是单一职责原则。我们来看看在iOS中本身自带的类或者方法哪些使用了单例的模式:

(1)UIAccelerometer类和sharedAccelerometer方法,一般如果方法名中有shared这样的词,就可以认为这是一个可以整个应用程序共享的实例变量,一般是使用了单例。

(2)UIApplication类和sharedApplication方法,我们一般使用该方法来创建全局变量。

(3)NSBundle类和mainBundle方法。

(4)NSFileManager类和defaultManager方法。

(5)NSNotificationCenter类和defaultManager方法。其中NSNotificationCenter也实现了观察者模式。

(6)NSUserDefaults类和defaultUser方法。

示例代码上传至:https://github.com/chenyufeng1991/iOS-Singleton   。


【单例实现】

(1)新建一个普通的类,假设名字为Singleton.   在Singleton.h中声明一个类方法,到时候使用该类方法(注意:一定是类方法,而不是实例方法)可以创建该类的唯一的一个实例:

[objc]  view plain  copy
 print ?
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @class Singleton;  
  4.   
  5. @interface Singleton : NSObject  
  6. // "+" 表示类的方法,由类调用  
  7. +(Singleton *)sharedInstance;  
  8.   
  9. @end  

(2)在Singleton.m中需要实现sharedInstance方法和你其他的业务逻辑:

[objc]  view plain  copy
 print ?
  1. #import "Singleton.h"  
  2.   
  3. // 用static声明一个类的静态实例;  
  4. static Singleton *_sharedInstance = nil;  
  5.   
  6. @implementation Singleton  
  7.   
  8. /** 
  9.  *  1.使用类方法生成这个类唯一的实例; 
  10.  */  
  11. +(Singleton *)sharedInstance{  
  12.     if (!_sharedInstance) {  
  13.         _sharedInstance =[[self alloc]init];  
  14.     }  
  15.     return _sharedInstance;  
  16. }  
  17.   
  18. @end  

注意:一定要声明一个static的静态变量。以后创建类的唯一实例就使用sharedInstance方法,而不是使用alloc ,init.


(3)我们使用一个简单的demo来演示一下单例:

[objc]  view plain  copy
 print ?
  1. #import "RootVC.h"  
  2. #import "Singleton.h"  
  3.   
  4. @interface RootVC ()  
  5.   
  6. @end  
  7.   
  8. @implementation RootVC  
  9.   
  10. - (void)viewDidLoad  
  11. {  
  12.   [super viewDidLoad];  
  13.   
  14.   [self testSigleTon];  
  15. }  
  16.   
  17. -(void)testSigleTon  
  18. {  
  19.   //单例的结果就是,调用类方法,只返回一个共有的对象  
  20.   /** 
  21.    *  single和single2是同一个对象; 
  22.    因为返回的数据是一个静态变量,全局唯一; 
  23.    */  
  24.   Singleton *single = [Singleton sharedInstance];  
  25.   Singleton *single2 = [Singleton sharedInstance];  
  26.   
  27.   if (single == single2) {  
  28.     NSLog(@"single == single2");  
  29.   }  
  30.   
  31.   NSLog(@"single地址:%@",single);  
  32.   NSLog(@"single2地址:%@",single2);  
  33.   
  34.   
  35. }  
  36.   
  37. @end  

(4)输出结果如下:



      可以看到,两个对象的内存地址是一样的,表示这两个对象其实是同一个对象,单例也就实现了。这是单例最普遍也是最简单的实现方式,在项目中会经常用到,在不涉及多线程的情况下是完全正确的。但是,我们再多想一想,在多线程开发中,这种实现方式是否安全呢?那么应该如何实现。


【单例架构】

       在项目开发中,如果我们像上述实现方法一样,在每个类中都使用这样写一个方法来生成单例,会不会显得很麻烦,很冗余。这样重复在每个类中重复写代码不利于开发与架构,那么我们应该使用什么方法来进行代码抽取呢?解决方案就是使用类别(Category)。关于Category类别的简要介绍,请参考《Objective-C——类别(Category)详解》。具体的实现如下:

(1)新建一个Category,作为对NSObject类的扩展。因为NSObject类是大部分iOS类的基类,如果使用Category为NSObject增加额外方法(shareInstance方法),那么所有继承自NSObject的类都可以使用该方法。我们常用的UIViewController和UIView都是从NSObject继承的,这样就会很方便。



(2)类别Category生成以后文件如下:


需要在NSObject+Singleton.h头文件中对外暴露一个生成实例的方法,供其他类调用。

[objc]  view plain  copy
 print ?
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface NSObject (Singleton)  
  4.   
  5. // "+" 表示类的方法,由类调用  
  6. + (instancetype)sharedInstance;  
  7.   
  8. @end  


(3)在NSObject+Singleton.m中需要实现上述方法,用来生成某一个类的唯一实例。我这里使用字典来存储某一个类和该类的实例,也就是键值对的形式:键是类名,值是对象。根据类名去检索该类的对象是否已经被创建,如果检索到类名,表示已经被创建,则直接返回对象;如果没有检索到类名,则需要创建,创建完成后也存储到字典中;

[objc]  view plain  copy
 print ?
  1. #import "NSObject+Singleton.h"  
  2.   
  3. @implementation NSObject (Singleton)  
  4.   
  5. //使用可变字典存储每个类的单一实例,键为类名,值为该类的对象;  
  6. //声明为静态变量,可以保存上次的值;  
  7. static NSMutableDictionary *instanceDict;  
  8. id instance;  
  9.   
  10. + (instancetype)sharedInstance {  
  11.   @synchronized(self)  
  12.   {  
  13.     //初始化字典;  
  14.     if (instanceDict == nil) {  
  15.       instanceDict = [[NSMutableDictionary alloc] init];  
  16.     }  
  17.   
  18.     //获取类名;  
  19.     NSString *className = NSStringFromClass([self class]);  
  20.     if (className) {  
  21.       //查找字典中该类的对象,使用类名去进行查找,可以确保一个类只被存储一次;  
  22.       instance = instanceDict[className];  
  23.       if (instance == nil) {  
  24.         //该类的对象还没实例化,就进行初始化,并根据键值对的形式存储;  
  25.         instance = [[self.class alloc] init];  
  26.         [instanceDict setValue:instance forKey:className];  
  27.       }else{  
  28.         //该类对象已经存储在字典中,直接返回instance即可;  
  29.       }  
  30.     }else{  
  31.       //没有获取类名,所以确保sharedInstance是一个类方法,用类进行调用;  
  32.     }  
  33.   
  34.     return instance;  
  35.   }  
  36. }  
  37. @end  

(4)单例的category已经写完,下面将要进行测试。我这里的测试方法如下:两个界面之间进行跳转并返回,使用相同的代码生成类对象;同时新建一个Person类和StudentModel类来测试,两个类都分别继承自NSObject,里面没有任何实现,只用来创建对象。别忘了导入头文件#import "NSObject+Singleton.h".

第一个界面ViewController.m实现如下:

[objc]  view plain  copy
 print ?
  1. #import "ViewController.h"  
  2. #import "NSObject+Singleton.h"  
  3. #import "Person.h"  
  4. #import "StudentModel.h"  
  5.   
  6. @interface ViewController ()  
  7.   
  8. @end  
  9.   
  10. @implementation ViewController  
  11.   
  12. - (void)viewDidLoad {  
  13.   [super viewDidLoad];  
  14.   
  15. }  
  16.   
  17. - (void)viewDidAppear:(BOOL)animated{  
  18.   
  19.   [super viewDidAppear:true];  
  20.   
  21.   //使用sharedInstance创建类对象;  
  22.   ViewController *vc1 = [ViewController sharedInstance];  
  23.   ViewController *vc2 = [ViewController sharedInstance];  
  24.   NSLog(@"ViewController---vc1地址:%@",vc1);  
  25.   NSLog(@"ViewController---vc2地址:%@",vc2);  
  26.   
  27.   if (vc1 == vc2) {  
  28.     NSLog(@"ViewController---vc1 == vc2");  
  29.   }  
  30.   
  31.   //循环创建5个Person对象,5个对象都相同;  
  32.   for (int i = 0; i < 5; i++) {  
  33.     Person *per1 = [Person sharedInstance];  
  34.     NSLog(@"ViewController---per1地址:%@",per1);  
  35.   }  
  36.   
  37.   //使用alloc创建对象,每个对象都是不同的;  
  38.   for (int i = 0; i < 5; i++) {  
  39.     StudentModel *stud = [[StudentModel alloc] init];  
  40.     NSLog(@"ViewController---stud地址:%@",stud);  
  41.   }  
  42.   
  43.   
  44. }  
  45.   
  46. @end  


第二个界面SecondViewController.m实现如下:

[objc]  view plain  copy
 print ?
  1. #import "SecondViewController.h"  
  2. #import "NSObject+Singleton.h"  
  3. #import "Person.h"  
  4. #import "StudentModel.h"  
  5. #import "ViewController.h"  
  6.   
  7. @interface SecondViewController ()  
  8.   
  9. @end  
  10.   
  11. @implementation SecondViewController  
  12.   
  13. /** 
  14.  *  在另一个界面中做同样的测试; 
  15.  */  
  16. - (void)viewDidLoad {  
  17.   [super viewDidLoad];  
  18.   
  19. }  
  20.   
  21. - (void)viewDidAppear:(BOOL)animated{  
  22.   
  23.   [super viewDidAppear:animated];  
  24.   
  25.   SecondViewController *secondVc1 = [SecondViewController sharedInstance];  
  26.   SecondViewController *secondVc2 = [SecondViewController sharedInstance];  
  27.   
  28.   NSLog(@"SecondViewController---secondVc1地址:%@",secondVc1);  
  29.   NSLog(@"SecondViewController---secondVc2地址:%@",secondVc2);  
  30.   
  31.   if (secondVc1 == secondVc2) {  
  32.     NSLog(@"SecondViewController---secondVc1 == secondVc2");  
  33.   }  
  34.   
  35.   for (int i = 0; i < 5; i++) {  
  36.     Person *per1 = [Person sharedInstance];  
  37.     NSLog(@"SecondViewController---per1地址:%@",per1);  
  38.   }  
  39.   
  40.   for (int i = 0; i < 5; i++) {  
  41.     StudentModel *stud = [[StudentModel alloc] init];  
  42.     NSLog(@"SecondViewController---stud地址:%@",stud);  
  43.   }  
  44.   
  45. }  
  46.   
  47. /** 
  48.  *  返回上一界面,再次生成对象查看; 
  49.  * 
  50.  *  @param sender <#sender description#> 
  51.  */  
  52. - (IBAction)back:(id)sender {  
  53.   
  54.   [self dismissViewControllerAnimated:true completion:nil];  
  55. }  
  56.   
  57. @end  


下面分别是三个步骤打印log:启动第一个界面、跳转到第二个界面、返回第一个界面。

启动第一个界面的输出:



跳转到第二个界面的输出:



再次返回到第一个界面的输出:



      总结,通过以上打印输出,使用sharedInstance创建单例后,无论在哪一个界面,每个类的对象是唯一的。而使用alloc创建的对象往往都是不同的。通过以上的设计,就不需要在每一个类中都去实现sharedInstance方法了。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

最近极客学院Wiki正在进行IT职业技能图谱的制定,我主要负责iOS方向,大家感兴趣的可以一起参加,有问题或者修改可以直接给我发issues或者pull request。https://github.com/chenyufeng1991/skillmap  。


猜你喜欢

转载自blog.csdn.net/denggun12345/article/details/79293155