ios-4-创建单例模式

单例模式是在实际项目开发中用到比较多的一种设计模式,设计原理是整个系统只产生一个对象实例,通过一个统一的方法对外提供这个实例给外部使用。

在Java中,构造单例一般将类的构造函数声明为private类型,然后通过一个静态方法对外提供实例对象,那么,在OC中,如何实现单例的,请看下面完整代码。

 

@implementation Car

//声明一个静态对象引用并赋为nil

static Car *sharedInstance= nil;

 

//声明类方法(+为类方法,也就是Java中的静态方法

+(Car *) sharedInstance

{

     if(!sharedInstance)

     {

          sharedInstance = [[self alloc] init];

     }

     return sharedInstance;

}

@end

 

//覆盖allocWithZone:方法可以防止任何类创建第二个实例。使用synchronized()可以防止多个线程同时执行该段代码(线程锁)

 

+(id)allocWithZone:(NSZone *) zone

{

     @synchronized(self)

     {

          if(sharedInstance == nil)

          {

               sharedInstance = [super allocWithZone:zone];

               return sharedInstance;

          }

     }

     return sharedInstance;

}

前端-语言
原文地址:https://www.cnblogs.com/beesky520/p/3831669.html