[oc學習日記]單例模式,oc學習日記

來源:互聯網
上載者:User

[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>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.