首页 > 移动开发 > iOS > 单例模式
2019
02-28

单例模式

单例模式就是只有一个实例,它确保一个类只有一个实例,并且自行实例化并向整个系统提供这个实例。它经常用来做应用程序级别的共享资源控制。这个模式使用频率非常高,通过一个单例类,可以实现在不同窗口之间传递数据。

在objective-c中要实现一个单例类,至少需要做以下四个步骤:
1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,
3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实例的时候不产生一个新实例,
4、适当实现allocWitheZone,copyWithZone,release和autorelease,retain方法

static MySampleClass* singleInstance = nil;//static 静态实例是关键

+ (MySampleClass*) Instance
{
  @synchronized(self){
    if(singleInstance == nil) {
      [[self alloc] init];// assignment not done here
    }
  }
  return singleInstance;
}

+ (id)allocWithZone:(NSZone*)zone
{
  @synchronized(self){
    if(singleInstance == nil) {
      singleInstance = [super allocWithZone:zone];
      return singleInstance;  // 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
}

- (oneway void)release
{
   //do nothing
}

- (id)autorelease
{
   return self;
}

 

最后编辑:
作者:老虎, 嘟嘟啦
这个作者貌似有点懒,什么都没有留下。

留下一个回复

你的email不会被公开。