ObjectiveC中的单例设计模式

注意class method中什么时候用self,什么时候用super!

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
50
51
52
53
54
55
56
#import "PostOfficeProxy.h"  
#import "HTTPPostOffice.h"
static PostOffice *_sharedPostOffice = nil;
@implementation PostOfficeProxy
@synthesize realPostOffice;
+ (PostOffice*)sharedPostOfficeProxy {
NSLog(@"shared");
@synchronized([PostOffice class]) {
if (nil == _sharedPostOffice) {
[[self alloc] init];

}
}
return _sharedPostOffice;
}
+ (id)allocWithZone:(NSZone *)zone {
NSLog(@"alloc zone");
@synchronized([PostOffice class]) {
if (nil == _sharedPostOffice) {
_sharedPostOffice= [super allocWithZone:zone];


}
}
return _sharedPostOffice;
}
- (id)init {
NSLog(@"init");
self = [super init];
if (nil != self) {
self.realPostOffice = [[HTTPPostOffice alloc] init];
}

return self;

}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX;
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
@end

觉得本文有帮助,长按二维码进行微信打赏