1 single-Case mode
It is a design pattern (common design patterns are: Observer mode, Factory mode, façade mode, etc.). In a singleton design pattern, a class has only one instance, allocates memory space once, saves memory, etc., and is especially suitable for use on the mobile side.
To achieve a single example of the idea:
1 can only allocate memory once--to intercept the Alloc method
The bottom of the 2 Alloc method is the Allocwithzone method
3 Each class has only one object and needs to have a global variable to store the object
4 thread safety needs to be considered
1.1 Single-Case basic form (ARC) – Lazy mode 1.1.1. h file
@interface MusicTool : NSObject//给外界快速生成单例对象使用+(instancetype)sharedMusicTool;@end
1.1.2. m file
@implementation Musictool//① defines a global static variable that is used to store the created Singleton object, returning the static ID _instance;//② implementing the method in the header file (Instancetype) when required by the outside world sharedmusictool{//Avoid locking every thread, first judge once, if empty will continue to lock and create the object if (_instance = = nil) {//Avoid multiple threads creating _instance, Lock @synchronized (self) {//using lazy loading, make sure _instance only creates once if (_instance = = nil) { _instance = [[Self alloc]init]; }}} return _instance;} ③ rewrite Allocwithzone: Method---Memory is basically the same as Sharedmusictool method body + (Instancetype) Allocwithzone: (struct Nszone *) zone{// Avoid locking every thread, first judge once, if it is empty will continue to lock and create the object if (_instance = = nil) {//Avoid multiple threads to create _instance at the same time, lock @synchronized (sel f) {//Use lazy loading, make sure _instance only creates once if (_instance = = nil) {//Call parent class Party method, allocating space _instance = [Super Allocwithzone:zone]; }}} return _instance;} ④ override Copywithzone: method to avoid the copy operation of the instance object causing the creation of a new object-(Instancetype) Copywithzone: (Nszone *) zone{//Because it is an object method, it indicates that there may be a _instance object, return directly to _instance;} @end
1.1.3 Code Explanation (1) Why are global variables using static?
①static modifying local variables
* Its life cycle is the same as the global variable, until the end of the program, only one copy of memory space
* Scope is not changed
②static Modifying global variables
* Only one copy of memory space
* Global variables, in other files, can be declared by extern ID _instance, and then called directly in other files. After the static modification, the other file cannot be referenced after the extern ID _instance declaration
(2) The principle of locking and lazy loading
Lazy loading is to make sure that the entire class has only one _instance, to do a singleton
Locking: Multiple threads may find the current _instance==nil, then the object will be created at the same time, not conform to the principle of singleton, so lock. However, the lock is easy to reduce the efficiency, not every time the thread to lock, so in the lock before the first judge whether it is empty, not empty at all do not need to create, directly return. Empty indicates that the object may need to be created and then locked.
1.2 GCD Simplified single case (ARC)
In the Allocwithzone method and Sharedsoundtool, each time you need to determine whether it is empty, and then lock, the purpose is to ensure that [[self alloc]init] and [super Allocwithzone:zone] code is executed only once, Then you can use GCD one-time code to solve, in addition, the GCD disposable code is thread-safe, so we do not need to handle the lock problem ourselves.
//修改 sharedSoundTool 方法+(instancetype)sharedSoundTool{ dispatch_once_t onceToken = NULL; dispatch_once(&onceToken) { _instance = [[self alloc]init]; } return _instance;}//修改 allocWithZone 方法+(instancetype)allocWithZone:(struct NSZone *)zone{ dispatch_once_t onceToken = NULL; dispatch_once(&onceToken) { _instance = [super allocWithZone:zone]; } return _instance;}
1.3 GCD Simplified single case (MRC)
In the MRC environment, we need to consider what to do if the singleton object that was created is manually released. So we need to consider this when designing a singleton pattern. As follows:
* Retain, once the singleton object is created, there is only one object globally, so be sure to ensure that the retain is still itself and the reference count is constant
* release, because there is only one object, can not be released after release, so release operations need to intercept
* Autorelease, same as release
* Retaincount, always guarantee that the reference counter is 1
So in the MRC environment, when designing a singleton pattern, you also need to rewrite the following four methods
//重写 retain 方法,不作计数器加1的操作-(instancetype)retain{ return _instance;}//重写 release 方法,不做任何操作-(void)release{}//重写 autorelease 方法,返回自身-(instancetype)autorelease{ return _instance;}//重写 retainCount 方法,返回1-(NSUInteger)retainCount{ return 1;}
1.4 A Hungry man mode (not used)
The singleton is usually divided into two modes: the lazy and a hungry man modes.
Lazy mode
When using this singleton object, the object is created, which is the lazy loading form of _instance. This approach works best because of limited memory on mobile devices.
A Hungry man mode
When the class is first loaded, a singleton object is created and saved in _instance. Since the first load was created, the memory was allocated from the time the program started running and was not suitable for mobile devices.
Load and Initilized methods
Load method
①当程序刚开始运行的时候,所有的类都会加载到内存中(不管这个类有没有使用),此时就会调用 load 方法 ②如果某种操作想要在程序运行的过程中只执行一次,那么这个操作就可以放到 load 方法中③基于第二点,我们的饿汉模式的单例对象创建就放在 load 方法中
Initialized method
①当类第一次被使用的时候调用(比如,调用类的方法)。②如果子类没有重写该方法,那么父类的initialized方法可能会被执行多次。所以饿汉模式不能使用这个方法
. h file
@interface SoundTool():NSObejct//提供外界访问的方法+(instancetype)sharedSoundTool;@end
. m file
@implementation SoundTool//①定义静态全局变量static id _instance;//②实现方法+(instancetype)sharedSoundTool{ return _instance;}//③重写load方法+(void)load{ //不需要线程安全,类加载的时候线程还没开始呢 _instance = [[self alloc]init];}//④重写allocWithZone方法+(instancetype)allocWithZone:(struct _NSZone *)zone{ if(_instance == nil) { _instance = [super allocWithZone:zone]; } return _instance;}@end
1.5 Arc and MRC adaptation
The above single-case design is divided into arc and MRC environments. MRC has more code related to retain and release than arc. In order to be able to adapt the same code to different environments, we can use conditional compilation directives.
#if __has_feature(objc_arc)//ARC编译环境#else//MRC编译环境-(instancetype)retain{return _instance;}-(void)release{}-(instancetype)autorelease{return _instance;}-(NSUIngeter)retainCount{return 1;}#endif
1.6 Macro Implementation Single case
Because the single h file and M file are immutable, the macro definition can be pumped. The definition of the macro should be noted
1 macro definition If you want to replace a character, you need to use # #拼接
#define SoundToolH(name) +(instancetype)shared##name;//调用宏定义SoundToolH(MusicTool)时,就相当于+(instancetype)sharedMusicTool;
2 macro definition If a line break appears, you need to mark the next line as part of the macro definition with the symbol "\", but the end of the last line does not need
#define SoundToolM(name) static id _instance; +(instancetype)shared##name { dispatch_once_t onceToken = NULL; dispatch_once(&onceToken) { _instance = [self alloc]init]; } }
iOS Singleton mode