标签:
iOS设计模式 - 单例
原理图
说明
1. 单例模式人人用过,严格的单例模式很少有人用过
2. 严格的单例模式指的是无法通过常规的 alloc init 方法来生成对象,派生出来的子类也不能产生出对象,而只能通过单例的方法获取到对象
源码
https://github.com/YouXianMing/SingletonPattern
// // Singleton.h // SingletonPattern // // Created by YouXianMing on 15/8/6. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface Singleton : NSObject + (Singleton *)sharedInstance; @end
// // Singleton.m // SingletonPattern // // Created by YouXianMing on 15/8/6. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "Singleton.h" #define STR_SINGLETON @"STR_SINGLETON" static Singleton *_sharedSingleton = nil; @implementation Singleton + (Singleton *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sharedSingleton = (Singleton *)STR_SINGLETON; _sharedSingleton = [[Singleton alloc] init]; }); return _sharedSingleton; } - (instancetype)init { NSString *string = (NSString *)_sharedSingleton; if ([string isKindOfClass:[NSString class]] && [string isEqualToString:STR_SINGLETON]) { self = [super init]; if (self) { } return self; } else { return nil; } } @end
细节
保证只能从shareInstance方法获取实例的技巧
标签:
原文地址:http://www.cnblogs.com/YouXianMing/p/4709209.html