设计模式----单例模式

单例模式需要达到的目的

1. 封装一个共享的资源

2. 提供一个固定的实例创建方法

3. 提供一个标准的实例访问接口

 

在iOS中有很多单例对象,比如UIApplication,UIScreen等等。

//.h文件
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
//单例方法
+(instancetype)sharedSingleton;
@end
//.m文件
#import "Singleton.h"
@implementation Singleton
//全局变量
static id _instance = nil;
//单例方法
+(instancetype)sharedSingleton{
    return [[self alloc] init];
}
////alloc会调用allocWithZone:
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    //只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
//初始化方法
- (instancetype)init{
    // 只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super init];
    });
    return _instance;
}
//copy在底层 会调用copyWithZone:
- (id)copyWithZone:(NSZone *)zone{
    return  _instance;
}
+ (id)copyWithZone:(struct _NSZone *)zone{
    return  _instance;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
    return _instance;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}
@end

单例模式使用

[plain 

[[SingletonClass sharedInstance] xxx];  

 

单例的销毁

销毁也就是对单例的释放,在应用终止的时候实现,delegate方法如下。

 

[plain]  

- (void)applicationWillTerminate:(UIApplication *)application  

{  

    [SingletonClass destroyDealloc];  

}  

 

 

销毁方法

[plain]  

+ (void)destroyDealloc  

{  

    if ([getInstance retainCount] != 1)  

        return;  

      

    [getInstance release];  

    getInstance = nil;  

}  

 




(重点)另外一种单例的创建:http://blog.csdn.net/lovefqing/article/details/8516536


原文地址:https://www.cnblogs.com/meixian/p/6086995.html