[oc学习日记]单例模式
来源:互联网 发布:大话数据库在线 编辑:程序博客网 时间:2024/05/17 23:35
下面我们就由一个学生类举例说明
因为要保证系统只有一个对象就要重写对象的创建方法,对象的拷贝方法
1 #import <Foundation/Foundation.h>2 //因为要重写拷贝方法,所以要遵循拷贝协议3 @interface Student : NSObject<NSCopying,NSMutableCopying>4 +(id)create;//声明创建对象的方法5 @end
接下来我们再来看这些方法的实现过程
注意事项:
1.一定要先创建一个静态全局的对象(确保只有一个地址的保障)
2.重写alloc和new的创建方法时,使用类名创建会出错,所以要用super
3.为防止多线程操作冲突,要用@synchronized进行避免
1 #import "Student.h" 2 //首先要创建一个静态全局的对象 3 static Student *stu = nil; 4 @implementation Student 5 +(id)create//实现创建对象的方法 6 { 7 @synchronized (self)//防止多线程操作冲突 8 { 9 if (stu == nil) {10 stu = [[Student alloc]init];//如果对象为空的话,就创建新对象,否则返回,保证只有一个对象11 }12 return stu;13 }14 }15 //重写alloc和new的创建对象方法16 +(instancetype)allocWithZone:(struct _NSZone *)zone17 {18 @synchronized (self)19 {20 if (stu == nil) {21 stu = [[super allocWithZone:zone]init];//如果对象为空的话,就创建新对象,否则返回,保证只有一个对象22 }23 return stu;24 }25 }26 //重写浅拷贝方法27 -(id)copyWithZone:(NSZone *)zone28 {29 return stu;30 }31 //重写深拷贝方法32 -(id)mutableCopyWithZone:(NSZone *)zone33 {34 return stu;35 }36 @end
主函数的实现
我们虽然在主函数中定义了很多student的方法,但是所有对象的空间只有一个
1 #import <Foundation/Foundation.h> 2 #import "Student.h" 3 int main(int argc, const char * argv[]) { 4 @autoreleasepool { 5 Student *stu = [[Student alloc]init]; 6 Student *stu1 = [[Student alloc]init]; 7 Student *stu2 = [Student new]; 8 Student *stu3 = [stu copy]; 9 Student *stu4 = [stu mutableCopy];10 NSLog(@"\n%@\n%@\n%@\n%@\n%@",stu,stu1,stu2,stu3,stu4);11 }12 return 0;13 }
主函数的运行效果
2015-06-05 09:17:48.274 day26_01[643:12774] <Student: 0x100304460><Student: 0x100304460><Student: 0x100304460><Student: 0x100304460><Student: 0x100304460>
0 0
- [oc学习日记]单例模式
- OC学习日记014-单例模式和委托模式
- [oc学习日记]代理模式
- 2017.01.04 学习日记-单例模式
- OC学习篇之---单例模式
- OC学习笔记之单例模式
- OC学习篇之-----单例模式
- OC 单例模式
- OC单例模式
- oc 单例模式
- OC-单例模式
- OC - 单例模式
- OC-单例模式
- oc单例模式
- oc单例模式
- OC单例模式
- OC-单例模式
- Android设计模式学习日记04--单例模式
- dup和dup2函数的不同和使用
- SDN初探–openflow实验记录(ubuntu+mininet+opendaylight)
- appium简明教程(10)——控件定位基础
- NGS项目二:提高数据信息收集整合能力
- 【leetcode】Linked List Cycle II
- [oc学习日记]单例模式
- Java读取属性文件
- 混淆——proguard.cfg文件
- 发现一个大牛Scott Lowe博客
- 使用Nginx+FFMPEG搭建HLS直播转码服务器
- 国生教育:自考必看的临场得分策略
- 学习数据库无法正常启动,修改Undo表空修复法
- appium简明教程(11)——使用resource id定位(仅支持安卓4.3以上系统)
- 在 jboss-5.1.0.GA中编写 会话Bean和MDB