码迷,mamicode.com
首页 > 移动开发 > 详细

ios设计模式——单例模式

时间:2015-09-19 22:46:49      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

一、定义


  • 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

  如何保证只能创建一个实例

二、使用


  1. 类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问
  2. 这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码

三、代码


  • 方法一
     1 #import "Singleton.h"
     2 
     3 @implementation Singleton
     4 
     5 static Singleton * shared = nil;
     6 
     7 + (Singleton *)sharedInstance
     8 {
     9     static dispatch_once_t once;
    10     dispatch_once(&once, ^{
    11             shared = [[super allocWithZone:NULL] init];
    12     });
    13     
    14     return shared;
    15 }
    16 
    17 + (instancetype)allocWithZone:(struct _NSZone *)zone
    18 {
    19     return [self sharedInstance];
    20 }
    21 
    22 @end

     

  调用:

 1        Singleton * single = [[Singleton alloc] init];
 2         NSLog(@"%@", single);
 3         
 4         Singleton * sing = [Singleton sharedInstance];
 5         NSLog(@"%@", sing);
 6         
 7         Singleton * single1 = [[Singleton alloc] init];
 8         NSLog(@"%@", single1);
 9         
10         Singleton * sing1 = [Singleton sharedInstance];
11         NSLog(@"%@", sing1);

输出结果:

技术分享

这样,当我们调用alloc的时候,会自动调用+ (instancetype)allocWithZone:(struct _NSZone *)zone方法,调用这个方法的时候,就会调用sharedInstance方法,所以这样不管什么时候使用这个类,最终都是由sharedInstance返回的,而且,sharedInstance方法,只初始化该对象一次,所以返回的地址都是一样的。

  • 方法二
 1 #import "Singleton.h"
 2 
 3 @implementation Singleton
 4 
 5 static Singleton * shared = nil;
 6 
 7 + (Singleton *)sharedInstance
 8 {
 9     if(shared == nil){
10         shared = [[self alloc] init];
11     }
12     return shared;
13 }
14 
15 + (instancetype)allocWithZone:(struct _NSZone *)zone
16 {
17     static dispatch_once_t once;
18     dispatch_once(&once, ^{
19         shared = [[super allocWithZone:zone] init];
20     });
21     
22     return shared;
23 }
24 
25 @end

方法一和方法二,执行的效果是一样的,只是函数的执行数序是不同的,方法一不管调用哪个方法,最后调用的一个是sharedInstance,而方法二,不管调用哪一个函数,最终调用的是allocWithZone。其实底层实现都是一样的,最终都由[[super allocWithZone:zone] init]返回一个地址给static对象。

 

 
 

ios设计模式——单例模式

标签:

原文地址:http://www.cnblogs.com/sjzlovecj/p/4822366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!