`

iPhone中的单例模式(两种方式)

阅读更多
=====================================================
原帖:http://www.cnblogs.com/lyanet/archive/2013/01/11/2856468.html
单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

1.单例模式的要点:

  显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

2.单例模式的优点:

  1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。
  2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程

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

=====================================================
两种方式:
原帖:http://webfrogs.me/2013/04/01/ios-singleton/
单例模式算是开发中比较常见的一种模式了。在iOS中,单例有两种实现方式(至少我目前只发现两种)。
根据线程安全的实现来区分,
一种是使用@synchronized
另一种是使用GCD的dispatch_once函数。
=====================================================

GlobalConstant.h

#import <Foundation/Foundation.h>

@interface GlobalConstant : NSObject

//属性值
@property(nonatomic,copy) NSString *requestURL;
@property(nonatomic,copy) NSString *ID;
@property(nonatomic,copy) NSString *userID;
@property(nonatomic,copy) NSString *userName;

+(GlobalConstant *)defaultConstant;//这是关键

@end




#import "GlobalConstant.h"

static GlobalConstant *sharedSingleton = nil;
    
@implementation GlobalConstant

@synthesize ID;
@synthesize requestURL ;
@synthesize userID ;
@synthesize userName;
@synthesize goodsKillDic;

-(id)init {
    @synchronized(self) {
        self = [super init];
        requestURL = @"http://192.168.1.104/DemoTest/";
        return self;
    }
}

+(GlobalConstant *)defaultConstant {
   
    @synchronized(self)
    {
        if (!sharedSingleton)
            sharedSingleton = [[self alloc] init];
        return sharedSingleton;
    }
}

/**
+ (InstanceClass *)defaultInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [[GlobalConstant alloc] init];
    });
    return sharedSingleton;
}
*/

///重写allocWithZone方法 防止直接 alloc出现副本
+ (id) allocWithZone:(NSZone *)zone {
    @synchronized (self) {
        if (sharedSingleton == nil) {
            sharedSingleton = [super allocWithZone:zone];
            return sharedSingleton;
        }
    }
    return nil;
}

- (id) copyWithZone:(NSZone *)zone {
    return self;
}

(id)retain {
    return self;
}

- (unsigned) retainCount
{
    return UINT_MAX;
}

-(oneway void)release {
    
}

-(id)autorelease {
    return self;
}

@end
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics