Iphone 实现Singleton(单例)模式

Singleton模式经常来做应用程序级别的共享资源控制, 应该说这个模式的使用频率非常高, 现在来看看在Objective-C里面的实现方法.
要实现一个Singleton Class, 至少需要做以下四个步骤:
1. 为Singleton Object实现一个静态实例, 初始化, 然后设置成nil.
2. 实现一个实例构造方法(通常命名为 sharedInstance 或者 sharedManager)检查上面声名的静态实例是否为nil, 如果是则新建并返回一个本类实例.
3. 重写 allocWithZone: 方法来保证当其他人直接使用 alloc 和 init 试图获得一个新实例的时候不会产生一个新的实例.
4. 适当的实现 copyWithZone:, release, retain, retainCount 和 autorelease.

 

下面是一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
static
 MySingletonClass *sharedSingletonManager = nil
;
 
+ ( MySingletonClass*) sharedManager
{
@synchronized ( self) {
if ( sharedSingletonManager == nil ) {
[ [ self alloc] init] ; // assignment not done here
}
}
 
return sharedSingletonManager;
}
 
+ ( id ) allocWithZone:( NSZone *) zone
{
@synchronized ( self) {
if ( sharedSingletonManager == nil ) {
sharedSingletonManager = [ super allocWithZone:zone] ;
return sharedSingletonManager; // assignment and return on first allocation
}
}
 
return nil ; //on subsequent allocation attempts return nil
}
 
- ( id ) copyWithZone:( NSZone *) zone
{
return self;
}
 
- ( id ) retain
{
return self;
}
 
- ( unsigned ) retainCount
{
return UINT_MAX ; //denotes an object that cannot be released
}
 
- ( void ) release
{
//do nothing
}
 
- ( id ) autorelease
{
return self;
}

你可能感兴趣的:(object,iPhone,Class,Allocation)