UserController.h
#import <Foundation/Foundation.h>
@interface UserController : NSObject <NSCopying>
{
int _id;
}
@property (nonatomic,assign) int _id;
- (void) display;
+ (id) defaultUserController:(int) _id;
@end
UserController.m
#import "UserController.h"
static UserController* singleInstance = nil;
@implementation UserController
@synthesize _id;
- (void) display{
NSLog(@"id = %d,地址 = %p",_id,self);
}
+ (id) defaultUserController:(int) _id {
@synchronized (self) {
if (singleInstance == nil) {
singleInstance = [[[self class] alloc]init];
}
singleInstance._id = _id;
}
return singleInstance;
}
//下面的方法是为了确保单例对象
+ (id) allocWithZone:(NSZone *)zone {
if (singleInstance == nil) {
singleInstance = [super allocWithZone:zone];
}
return singleInstance;
}
-(id) retain {
return singleInstance;
}
-(NSUInteger) retainCount {
return UINT_MAX;
}
-(oneway void) release {
}
-(id) autorelease{
return singleInstance;
}
-(id) copyWithZone:(NSZone *)zone {
return singleInstance;
}
//确保单例对象方法结束
@end
main.m
#import <Foundation/Foundation.h>
#import "UserController.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
/*
创建单例对象的基本步骤:
1.声明一个单例对象的静态实例,并初始化为nil
2.创建一个类的类工厂方法,生成一个该类的实例,并且仅在这个类的实例为nil时才生成该类的实例
3.覆盖allocWithZone:方法,确保程序员在直接分配和初始化对象时,不会产生另一个该类的实例对象
4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保单例的状态
5.在多线程环境中,注意使用@synchronized关键字,确保静态实例被正确的创建和初始化
*/
UserController* uc1 = [UserController alloc];
uc1._id = 1;
[uc1 display];
UserController* uc2 = [[UserController alloc]init];
uc2._id= 2;
[uc1 display];
[uc2 display];
UserController* uc3 = [UserController defaultUserController:3];
[uc1 display];
[uc2 display];
[uc3 display];
UserController* uc4 = [uc1 copy];
UserController* uc5 = [uc2 retain];
[uc3 release];
[uc3 release];
[uc3 release];
[uc3 release];
[uc3 release];
UserController* uc6 = [uc3 autorelease];
[uc4 display];
[uc5 display];
[uc6 display];
/*
输出结果:
2013-06-07 14:44:51.165 单例对象设计模式[2830:403] id = 1,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.167 单例对象设计模式[2830:403] id = 2,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.167 单例对象设计模式[2830:403] id = 2,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.168 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.168 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.169 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.169 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.170 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
2013-06-07 14:44:51.170 单例对象设计模式[2830:403] id = 3,地址 = 0x7fb25ac14530
通过结果能够看到,uc1---uc6这6个对象都指向了同一个内存地址,实现了单例对象设计模式.
*/
}
return 0;
}