Objective c singleton design pattern

Creating a Singleton Instance

 

A singleton object acts as a kind of control center, directing or coordinating the services of the class. Your class should generate a singleton instance rather than multiple instances when there is conceptually only one instance (as with, for example, NSWorkspace). You use singleton instances rather than factory methods or functions when it is conceivable that there might be multiple instances one day.

To create a singleton as the sole allowable instance of a class in the current process, you need to have an implementation similar to the code below. This code does the following:

 Declare a static instance of your singleton object and initialize it to nil.

 

 In your class factory method for the class (named something like “sharedInstance” or “getInstance”),

generate an instance of the class but only if the static instance is nil.

 

 Override the allocWithZone: method to ensure that another instance is not allocated if someone tries to allocate and initialize an instance of your class directly instead of using the class factory method. Instead, just return the shared object.

 

 Implement the base protocol methods copyWithZone:, release, retain, retainCount, and autorelease to do the appropriate things to ensure singleton status. (The last four of these methods apply to memory-managed code, not to garbage-collected code.)

 

 

Creating a Singleton Instance

 

//

// MySingletonClass.m

// Created by Tracy E on 10-10-27.

// Copyright 2010 tracy.cpp@gmail.com  All rights reserved.

//

 

#import "MySingletonClass.h"

 

static MySingletonClass *singletonInstance = nil;

 

@implementation MySingletonClass

 

+ (id)getInstance {

     if (singletonInstance == nil)

     {

          singletonInstance = [[super allocWithZone:NULLinit];

     }

     return singletonInstance;

}

 

+ (id)allocWithZone:(NSZone *)zone

{

     return [[self getInstanceretain];

}

 

- (id)copyWithZone:(NSZone *)zone {

      return self;

}

- (id)retain {

      return self;

}

 

- (NSUInteger)retainCount {

       return NSUIntegerMax//denotes an object that cannot be released

}

 

- (void)release {

      //do nothing

}

 

- (id)autorelease {

      return self;

}

 

@end


转载于:https://my.oschina.net/bankofchina/blog/271359

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值