设计模式 --- 单例模式(Singleton)

一、概念

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

通俗的说来:单例模式用于当一个类只能有一个实例的时候。

1.单例模式需要达到的目的:
• 封装一个共享的资源
• 提供一个固定的实例创建方法
• 提供一个标准的实例访问接口

2.单例模式的要点:

显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

3.单例模式的优点:

1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。

2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程

IOS中的单例模式
在objective-c中要实现一个单例类,至少需要做以下四个步骤:
 
1、为单例对象实现一个静态实例,并初始化,然后设置成nil
①在.h文件中定义一个类方法,返回当前实例
1 @interface SingleInstance : NSObject
2 //定义一个类方法,返回当前对象的实例
3 + (instancetype) sharedInstance;
4 @end

 ②在.m文件中定义一个静态的当前单例对象的实例,并赋值为nil

 1 static SingleInstance *instance = nil; 

2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例

①第一种实现方法

 1 //防止多线程同时执行,而创建多个对象
 2     @synchronized(self)
 3     {
 4         //当前对象为空
 5         if (!instance)
 6         {
 7             instance = [[self alloc] init];
 8         }
 9         
10         return instance;
11     }

②第二种实现方法(推荐使用)

1 static dispatch_once_t onceToken;
2     dispatch_once(&onceToken, ^{
3         instance = [[self alloc] init];
4     });
5     
6     return instance;

3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例

 1 //alloc会触发,重新allocWithZone方法,防止通过alloc创建一个新的对象
 2 + (instancetype)allocWithZone:(struct _NSZone *)zone
 3 {
 4     if (!instance)
 5     {
 6         instance = [super allocWithZone:zone];
 7     }
 8     
 9     return instance;
10 }


4、适当实现allocWitheZone,copyWithZone,release和autorelease。

 1 + (id)copyWithZone:(struct _NSZone *)zone
 2 {
 3     return self;
 4 }
 5 
 6 + (id)mutableCopyWithZone:(struct _NSZone *)zone
 7 {
 8     return self;
 9 }
10 
11 - (instancetype)retain
12 {
13     return self;
14 }
15 
16 - (oneway void)release
17 {
18     
19 }
20 
21 - (instancetype)autorelease
22 {
23     return self;
24 }
25 
26 - (NSUInteger)retainCount
27 {
28     return MAXFLOAT;
29 }
原文地址:https://www.cnblogs.com/caohexin-Blog/p/5006692.html