当前位置:编程学习 > wap >>

IOS开发中单例模式使用详解

第一、基本概念
 
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问。
 
第二、在IOS中使用单例模式的情况
 
1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间
 
2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度
 
第三、创建单例模式的基本步骤
 
1.声明一个单例对象的静态实例,并初始化为nil
 
2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个
 
3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象
 
4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象
 
5.在多线程的环境中,注意使用@synchronized关键字 
 
 
[cpp] 
//  
//  UserContext.h  
//  SingleDemo  
//  
//  Created by andyyang on 9/30/13.  
//  Copyright (c) 2013 andyyang. All rights reserved.  
//  
  
#import <Foundation/Foundation.h>  
  
@interface UserContext : NSObject  
@property (nonatomic,retain) NSString *username;  
@property(nonatomic,retain)NSString *email;  
+(id)sharedUserDefault;  
@end  
 
[cpp] 
//  
//  UserContext.m  
//  SingleDemo  
//  
//  Created by andyyang on 9/30/13.  
//  Copyright (c) 2013 andyyang. All rights reserved.  
//  
  
#import "UserContext.h"  
  
static UserContext *singleInstance=nil;  
@implementation UserContext  
  
+(id)sharedUserDefault  
{  
    if(singleInstance==nil)  
    {  
        @synchronized(self)  
        {  
            if(singleInstance==nil)  
            {  
                singleInstance=[[[self class] alloc] init];  
                  
            }  
        }  
    }  
    return singleInstance;  
}  
  
+ (id)allocWithZone:(NSZone *)zone;  
{  
    NSLog(@"HELLO");  
if(singleInstance==nil)  
{  
    singleInstance=[super allocWithZone:zone];  
}  
    return singleInstance;  
}  
-(id)copyWithZone:(NSZone *)zone  
{  
    NSLog(@"hello");  
    return singleInstance;  
}  
-(id)retain  
{  
    return singleInstance;  
}  
- (oneway void)release  
  
{  
}  
- (id)autorelease  
{  
    return singleInstance;  
}  
  
- (NSUInteger)retainCount  
{  
    return UINT_MAX;  
}@end  
 
 
[cpp]  
#import <Foundation/Foundation.h>  
#import "UserContext.h"  
  
int main(int argc, const char * argv[])  
{  
  
    @autoreleasepool {  
          
       UserContext *userContext1=[UserContext sharedUserDefault];  
        UserContext *userContext2=[UserContext sharedUserDefault];  
        UserContext *userContext3=[[UserContext alloc] init];  
        UserContext *userContext4=[userContext1 copy];  
        // insert code here...  
        NSLog(@"Hello, World!");  
          
    }  
    return 0;  
}  
 
result:
补充:移动开发 , IOS ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,