自學iOS開發小功能之五:代理設計模式以及書寫規範

來源:互聯網
上載者:User

標籤:

一、基本概念

設計模式(Design pattern)是一套被反覆使用、多數人知曉的、經過分類編目的、代碼設計經驗的總結。使用設計模式是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。 毫無疑問,設計模式於己於他人於系統都是多贏的;設計模式使代碼編製真正工程化;設計模式是軟體工程的基石脈絡,如同大廈的結構一樣。

代理設計模式:我們買電飯鍋之類的,不會親自到廠家去買,而是在商超等地方購買,而商超就是廠家的代理

應用場合:1、對象B想監聽對象A的行為,讓對象B成為對象A的代理

       2、對象A發生的事想告知對象B,讓對象B成為對象A的代理

     3、對象A無法處理某些行為的時候,讓對象B幫忙處理,即讓對象B成為對象A的代理

二、代碼

Student.h

 1 #import <Foundation/Foundation.h> 2 //聲明一個協議 3 @class Student; //此處別落下 4 @protocol StudentProtocol <NSObject> 5 - (void)studentFindHouse:(Student *)student;//此處注意傳遞student 6 @end 7  8 @interface Student : NSObject 9 //學生需要找房子10 - (void)findHouse;11 //學生需要代理,注意用id12 @property (strong, nonatomic)id<StudentProtocol> delegate;13 14 @end

Student.m

#import "Student.h"@implementation Student- (void)findHouse{    NSLog(@"學生想找房子");    //通知代理幫忙找房子,前提是擁有找房子的能力    if ([self.delegate respondsToSelector:@selector(studentFindHouse:)]) {              [self.delegate studentFindHouse:self];    }}@end

LinkHome.h

1 #import <Foundation/Foundation.h>2 #import "Student.h"  //此處本應該寫@protocol StudentProtocol會更規範和好看一些,但不知道為啥會有警告找不到代理,不過程式正常運行3 @interface LinkHome : NSObject <StudentProtocol> //遵守代理4 @end

LinkHome.m

1 #import "LinkHome.h"2 #import "Student.h"3 @implementation LinkHome4 - (void)studentFindHouse:(Student *)student5 {6     //必須實現代理的方法7     NSLog(@"%s 幫忙找房子 ",__FUNCTION__);8 }9 @end

main.m

 1 main.m 2 #import <Foundation/Foundation.h> 3 #import "Student.h" 4 #import "LinkHome.h" 5 int main(int argc, const char * argv[]) { 6     @autoreleasepool { 7         Student *st = [[Student alloc] init]; 8         LinkHome *lh = [[LinkHome alloc] init]; 9         //學生找到LinkHome10         st.delegate = lh;11 12         [st findHouse];13     }14     return 0;15 }

結果

2016-04-26 17:06:19.689 代理設計模式練習[4151:676544] 學生想找房子2016-04-26 17:06:19.689 代理設計模式練習[4151:676544] -[LinkHome studentFindHouse:] 幫忙找房子 Program ended with exit code: 0

三、代理模式的書寫規範

 

 1.一般情況下, 當前協議屬於誰, 我們就將協議定義到誰的標頭檔中。

 

 2.協議的名稱一般以它屬於的那個類的類名開頭, 後面跟上protocol。

 

 3.協議中的方法名稱一般以協議的名稱protocol之前的作為開頭。

 

 4.一般情況下協議中的方法會將觸發該協議的對象傳遞出去

 

 5.一般情況下一個類中的代理屬於的名稱叫做 delegate

 

 6.當某一個類要成為另外一個類的代理的時候, 一般情況下在.h中用@protocol 協議名稱;告訴當前類 這是一個協議。 在.m中用#import真正的匯入一個協議的聲明

 

自學iOS開發小功能之五:代理設計模式以及書寫規範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.