IOS开发中单例模式使用详解
来源:互联网 发布:软件设计和程序员 编辑:程序博客网 时间:2024/06/07 02:33
第一、基本概念
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问。
第二、在IOS中使用单例模式的情况
1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间
2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度
第三、创建单例模式的基本步骤
1.声明一个单例对象的静态实例,并初始化为nil
2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个
3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象
4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象
5.在多线程的环境中,注意使用@synchronized关键字
//// 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
//// 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
#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;}
- IOS开发中单例模式使用详解
- iOS开发设计模式详解
- iOS开发:开发过程中单例模式的使用
- ios开发--UITabBarController使用详解
- iOS开发 FTP使用详解
- ios开发--UITabBarController使用详解
- iOS开发UIScrollView使用详解
- iOS开发 cocopods使用详解
- iOS 开发 MJRefresh使用详解
- IOS开发之----单例模式详解
- IOS开发之----单例模式详解
- iOS开发中MVC、MVVM模式详解
- iOS开发中单例设计模式、通知中心的使用
- IOS开发NSBundle对象使用详解
- 【iOS开发】---- UITabBarController的使用详解
- IOS开发NSBundle对象使用详解
- IOS开发NSBundle对象使用详解
- IOS开发 UIWebView使用详解(1)
- gdb调试
- 手动wifi连接
- cgroup--内存 限制内存测试
- printf in KEIL C51
- excel vba调用windows API快速查找文件
- IOS开发中单例模式使用详解
- COUNT(*)与COUNT(列名)的区别
- WSP Content Type
- 给Repeater控件里添加序号的5种方法
- 博客园搬家之mysql相关问题解决
- 贪心--poj3262
- CSS架构
- UTF8与GB2312
- JIRA简介