ObjC 设计模式(二)

本文总结了一下,单例模式。

单例模式原则要求:

  1. 需要保持控制整个程序生命周期中只有一个实例。“发起调用的对象(calling object)不能以其他方式实例化单例对象,否则有可能创建单例类的多个实例”
  2. 要重载一些方法,保证对单例对象实例化的限制应该和cocoa 框架的引用计数模型保持一致

需要重载的方法:

1
2
3
4
5
6
7
8
9
10
11
12
+(id)allocWithZone:(NSZone*) zone { return [[self sharedInstance] retain];}

- (id) copyWithZone:(NSZone*) zone {return self;}

—(idretain {return self;}

-(NSUInteger)retainCount { return NSUIntegerMax;}

- (void) release {}

- (id) autorelease {return self;}

单例模式中的重要问题,

  1. 子类化继承

利用(Foundation)的函数id NSAllocate (Class aclass, NSUInteger extraBytes, NSZone * zone),实例化任何一个对象。

改造单例方法的写法:

1
2
3
4
5
6
7
8
9
+ (instancetype) sharedInstance
{
if (_instance==nil)
{
_instance=[NSAllocateObject([self class],0,NULL)]init;
}

return _instance;
}
  1. 线程安全

使用@synchronized() 或NSLock 实现线程安全
或者使用 dispatch_once()函数

不同层次的单例写法

  1. 最常见最易理解也最灵活,但没有满足以上两个原则的写法,在要求不严格的情况下不要重载其他方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
static Class *_instance;
+ (instancetype)sharedInstance
{
if(_instace==nil)
{

_instance=[[super allocWithZone:Null] init];

}
return _instance;

}