1.什么是单例模式?  Singleton
  答:单例模式的意图是类的对象成为系统中唯一的实例,提供一个访问点,供客户类共享资源
  
2.什么情况下使用单例?
  答:1.类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,
         2.这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码


OC中的单例模式写法不同于JAVA和C#,因为OC创建对象有多种方式

所以,创建唯一的实例同时,我们也需要重写一些方法


#import <Foundation/Foundation.h>
@interface Singleton : NSObject
@property (nonatomic,assign) int num;
@property (nonatomic,copy) NSString *text;
+(instancetype)shareInstances;//唯一的实例对象
@end

#import "Singleton.h"
//创建一个全局的实例对象 Singleton *instances = nil;
@implementation Singleton //对实例对象初始化
+(instancetype)shareInstances{
if(istances == nil)
instances = [[Singleton alloc] init];
return instances;
}
//限制使用copy时,返回对象自己
-(id)copyWithZone:(NSZone*)zone{
return self;
} //返回对象自己,不让引用计数加1
-(id)retain{
return self;
}
//当使用这个方法创建对象时,如果实例对象存在,就返回自己,如果不存在,就创建一个
+(id)allocWithZone:(NSZone*)zone{
//线程保护,避免多线程产生多个
@synchronized(self){
if(instances == nil){
instances = [super allocWithZone:zone];
return instances;
}
}
return instances;
}
//引用计数返回最大值
-(NSUInteger)retainCount{
return NSUIntegerMax;
}
-(oneway void)release{
}
-(id)autorelease{
//这个实例对象不能被释放
}
@end

#import "Singleton.h"
int main(){
Singleton *ton = [Singleton shareInstances];
NSLog(@"ton.num = %d, ton.text = %@", ton.num,ton.text);


//为了避免使用[Singleton new]创建的对象,我们必须重写这些方法

return 0;
}