[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
原创粉丝点击