1、单例模式概念
1)什么是单例模式:(Singleton)
单例模式的意图是是的类的对象成为系统中唯一的实例,提供一个访问点,供客户类 共享资源。
2)什么情况下使用单例?
1、类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方法。
2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。
3)单例设计模式的要点:
(1) 某个类只能有一个实例。
(2)他必须自行创建这个对象
(3)必须自行向整个系统提供这个实例;
(4)为了保证实例的唯一性,我们必须将
-(id)copyWithZone:(NSZone )zone +(id)allocWithZone:(NSZone )zone -(id)retain
-(NSUInteger)retainCount
-(oneway void)release -(id)autorelease 的实现方法进行覆盖。
(5)这个方法必须是一个静态类
4)在OC中实现单例模式:
先创建一个单例类,即:
import
Tools.h
#import <Foundation/Foundation.h>
@interface Tools : NSObject<NSCopying> @property (nonatomic,assign) int num; @property (nonatomic,copy) NSString *text; +(instancetype)shareIntances;
@end
Tools.m
#import "Tools.h"
static Tools *instance = nil; @implementation Tools
+(instancetype)shareIntances{
if (instance==nil) {
instance = [[self allocWithZone:NULL] init]; }
return instance; }
-(id)copyWithZone:(NSZone *)zone{ return self;
}
+(id)allocWithZone:(NSZone *)zone{
@synchronized(self) { if (instance == nil) {
instance = [super allocWithZone:zone];
return instance; }
}
return instance;
} -(id)retain{
return self; }
-(NSUInteger)retainCount{
return NSUIntegerMax; }
-(oneway void)release{
} -(id)autorelease{
return self; }
@end
注意:所谓单例,即我们自己创建一个单例类,该类只能生成唯一的对象,即
用 if (sharesingleton == nil) 方法来保证唯一性,为了防止该对象被复制(copy) 或者retain 和 release 等操作,我们必须在所创建的单例的实现文件( .m 文件)中将父 类的这些方法给覆盖,该目的是为了保证单例模式的一个严谨性。