·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> [oc学习日记]单例模式

[oc学习日记]单例模式

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

首先来了解一下单例模式的概念

单例模式就是保证系统中只存在一个对象(只有一个地址)的模式

下面我们就由一个学生类举例说明

因为要保证系统只有一个对象就要重写对象的创建方法,对象的拷贝方法

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 *)zone
17 {
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 *)zone
28 {
29     return stu;
30 }
31 //重写深拷贝方法
32 -(id)mutableCopyWithZone:(NSZone *)zone
33 {
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>