M牛C原创博客——oc中设计模式之——单例模式

来源:互联网 发布:青岛海尔软件地址 编辑:程序博客网 时间:2024/06/07 10:49
单例模式是在实际项目开发中用到比较多的一种设计模式,设计原理是整个系统只产生一个对象实例,通过一个统一的方法对外提供这个实例给外部使用。
在Java中,构造单例一般将类的构造函数声明为private类型,然后通过一个静态方法对外提供实例对象,那么,在OC中,如何实现单例的,请看下面完整代码。
@implementation Car
//声明一个静态对象引用并赋为nil
static Car *sharedInstance= nil;
//声明类方法(+为类方法,也就是Java中的静态方法)
+(Car *) sharedInstance
{
if(!sharedInstance)
{
sharedInstance = [[self alloc] init];
}
returnsharedInstance;
}
@end
//覆盖allocWithZone:方法可以防止任何类创建第二个实例。使用synchronized()可以防止多个线程同时执行该段代码(线程锁)
+(id)allocWithZone:(NSZone *) zone
{
@synchronized(self)
{
if(sharedInstance == nil)
{
sharedInstance = [super allocWithZone:zone];
returnsharedInstance;
}
}
return sharedInstance;
}
0 0
原创粉丝点击