关于什么是单例,iOS中的单例模式是什么,自行爬页搜索。这里抛砖引玉,说说单例模式应该怎样实现。
直接上代码。
//
// Singleton.h
// SingletonDemo
//
// Created by WangBo on 3/9/16.
// Copyright © 2016 WangBo. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+ (instancetype)shareInstance;
@end
//
// Singleton.m
// SingletonDemo
//
// Created by WangBo on 3/9/16.
// Copyright © 2016 WangBo. All rights reserved.
//
#import "Singleton.h"
@implementation Singleton
static Singleton *_singleton = nil;
+ (instancetype)shareInstance {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_singleton = [[super allocWithZone:NULL] init];//调用super的allocWithZone方法,是因为self的该方法在下面被重载了
});
return _singleton;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
return [self shareInstance];
}
+ (id)copyWithZone:(struct _NSZone *)zone {
return [self shareInstance];
}
@end
//
// main.m
// SingletonDemo
//
// Created by WangBo on 3/9/16.
// Copyright © 2016 WangBo. All rights reserved.
//
#import "Singleton.h"
#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
// insert code here...
Singleton *singleton1 = [Singleton shareInstance];
NSLog(@"%@", singleton1);
Singleton *singleton2 = [Singleton shareInstance];
NSLog(@"%@", singleton2);
Singleton *singleton3 = [Singleton shareInstance];
NSLog(@"%@", singleton3);
}
return 0;
}
程序输出:
2016-03-09 19:27:31.375 SingletonDemo[11477:206113] <Singleton: 0x100302340>
2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>
2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>
Program ended with exit code: 0
我们可以看到,三个对象对应内存中同一个值。
说明:
1.之所以要重载allocWithZone、copyWithZone方法,是因为如果不这样做,客户端通过这两个方法会得到一个新的实例,违背了我们单例模式的思想;
2.本文使用dispatch_once函数实现单例Singleton的初始化,因此只会在程序运行周期中执行一次,保重了单例的单一性。同时满足了线程安全的要求。
3.考虑到线程安全,我们同样可以使用对self加锁的方式来实现,@synchronized、NSLock,自行爬文搜索。
收工!~