[oc學習日記]單例模式,oc學習日記
首先來瞭解一下單例模式的概念
單例模式就是保證系統中只存在一個對象(只有一個地址)的模式
下面我們就由一個學生類舉例說明
因為要保證系統只有一個對象就要重寫對象的建立方法,對象的拷貝方法
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>