在以前的一片文章中介绍了对象的拷贝相关知识:http://blog.csdn.net/jiangwei0910410003/article/details/41926531,今天咱们来看一下OC中的单例模式,单例模式在设计模式中用的多是最多的一种了,并且也是最简单的一种java
实现单例模式有三个条件设计模式
一、类的构造方法是私有的学习
二、类提供一个类方法用于产生对象测试
三、类中有一个私有的本身对象spa
针对于这三个条件,OC中都是能够作到的.net
一、类的构造方法是私有的设计
咱们只须要重写allocWithZone方法,让初始化操做只执行一次指针
二、类提供一个类方法产生对象code
这个能够直接定义一个类方法对象
三、类中有一个私有的本身对象
咱们能够在.m文件中定义一个属性便可
下面来看代码:
AdressBook.h
// // AdressBook.h // 35_Singleton // // Created by jiangwei on 14-10-13. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import <Foundation/Foundation.h> //设计单利类的目的,限制这个类只能建立一个对象 //构造方法为私有的 //保存一个全局的static变量 @interface AdressBook : NSObject + (AdressBook *)shareInstance; @end在.h文件中提供了一个类方法,用于产生对象的
AdressBook.m
// // AdressBook.m // 35_Singleton // // Created by jiangwei on 14-10-13. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import "AdressBook.h" static AdressBook *instance = nil;//不能让外部访问,同时放在静态块中的 @implementation AdressBook + (AdressBook *)shareInstance{ if(instance == nil){ instance = [[AdressBook alloc] init]; } return instance; } //限制方法,类只能初始化一次 //alloc的时候调用 + (id) allocWithZone:(struct _NSZone *)zone{ if(instance == nil){ instance = [super allocWithZone:zone]; } return instance; } //拷贝方法 - (id)copyWithZone:(NSZone *)zone{ return instance; } //须要重写release方法,不能让其引用+1 - (id)retain{ return self; } //须要重写release方法,不能让其引用-1 - (oneway void)release{ //do Nothing... } - (id)autorelease{ return self; } @end
static AdressBook *instance = nil;//不能让外部访问,同时放在静态块中的
+ (AdressBook *)shareInstance{ if(instance == nil){ instance = [[AdressBook alloc] init]; } return instance; }
//限制方法,类只能初始化一次 //alloc的时候调用 + (id) allocWithZone:(struct _NSZone *)zone{ if(instance == nil){ instance = [super allocWithZone:zone]; } return instance; }
//拷贝方法 - (id)copyWithZone:(NSZone *)zone{ return instance; } //须要重写release方法,不能让其引用+1 - (id)retain{ return self; } //须要重写release方法,不能让其引用-1 - (oneway void)release{ //do Nothing... } - (id)autorelease{ return self; }拷贝方法只能返回当前的单实例
retain和release方法不能进行引用的+1和-1操做
测试代码
main.m
// // main.m // 35_Singleton // // Created by jiangwei on 14-10-13. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import <Foundation/Foundation.h> #import "AdressBook.h" //单利模式 int main(int argc, const char * argv[]) { @autoreleasepool { AdressBook *book1 = [AdressBook shareInstance]; AdressBook *book2 = [AdressBook shareInstance]; NSLog(@"%@",book1); NSLog(@"%@",book2); } return 0; }两个指针指向的是同一个对象
总结
这一篇文章主要介绍了OC中的单例模式,同时咱们OC学习篇的系列章程也就结束了,固然这些并不表明OC中全部的内容,还有不少其余内容,咱们只有后面慢慢的去使用他才会愈来愈了解。