iOS设计模式之单例模式
2024-04-19 本文已影响0人
点滴86
单例模式
单例设计模式(Singleton Design Pattern):一个类只允许创建一个对象(或者实例),那这个类就是一个单例类,这种设计模式就叫作单例设计模式,简称单例模式。
有些数据在系统中只应该保存一份,就比较适合设计为单例类。比如,系统的配置信息类。除此之外,我们还可以使用单例解决资源访问冲突的问题。
单例的代码示例
@interface DMSingleton : NSObject <NSCopying>
+ (DMSingleton *)sharedSingleton;
@end
static DMSingleton *singleton = nil;
@implementation DMSingleton
+ (DMSingleton *)sharedSingleton
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[super allocWithZone:NULL] init];
});
return singleton;
}
// 重写方法 【必不可少】
+ (id)allocWithZone:(struct _NSZone *)zone
{
return [self sharedSingleton];
}
// 重写方法 【必不可少】
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
@end
- 注意事项1:创建时通过[[super allocWithZone:NULL] init];
- 注意事项2:重写+ (id)allocWithZone:(struct _NSZone *)zone 方法,返回调用[self sharedSingleton]
- 注意事项3:遵守NSCopying协议,实现- (id)copyWithZone:(NSZone *)zone 方法,直接返回self
DMSingleton *singleton = [DMSingleton sharedSingleton];
DMSingleton *one = [[DMSingleton alloc] init];
DMSingleton *two = [singleton copy];
通过这样设计,可以保证上面三种创建方式返回的都是同一个单例对象。