一·什么事代理模式?
代理模式是在oc中經常遇到的一種設計模式,那什么叫做代理模式呢? 舉個例子:有一租客, 他要租房子,可是他不知道哪兒有房子可租,於是他就找了中介,讓中介去幫他找房子,於是他和中介之間商定了一個協議,協議中寫明了中介需要做的事情是幫他找房子, 而中介就成為了租客的代理人, 即:他和中介之間有個協議,中介繼承該協議,於是中介就需要實現該協議中的條款成為代理人。
二、 代理模式的關鍵點:
A完成一件事,但是自己不能完成,於是他找個代理人B 替他完成這個事情,他們之間便有個協議 (protocol),B繼承該協議來完成A代理給他的事情。
三、實例分析
下面來例舉一個例子,學生與中介的例子,學生委托中介幫助租房子。
1.首先學生和中介要有協議,協議如下:
建立協議文件.h的步驟:
快捷鍵Command+n將出現一個界面,選擇Objective-C File—>Next 在下一個界面中在File欄中寫StudentProtocol,在File Type中選擇Protocol然后回車,協議的文件就建立好了
在StudentProtocol.h文件中
1 #import <Foundation/Foundation.h> 2 3 @protocol StudentProtocol <NSObject> 4 /* 5 協議要做的事兒 6 幫學生找房子 7 */ 8 -(void)studentFindHourse; 9 @end
2,再次聲明Intermediary(中介)類,即代理的人:
在Intermediary.h文件中
#import <Foundation/Foundation.h> #import "StudentProtocol.h" @interface Intermediary : NSObject<StudentProtocol>//實現該協議 @end
3.中介要干的事兒,實現文件,在Intermediary.m文件中
#import "Intermediary.h" @implementation Intermediary -(void)studentFindHourse { NSLog(@"%s 幫學生找房子",__func__); //__func__輸出中介的名稱 } @end
4.在聲明一個Student類
在Student.h文件中
#import <Foundation/Foundation.h> #import "StudentProtocol.h" @interface Student : NSObject -(void)findHourse;//找房子的方法 @property(assign,nonatomic)id <StudentProtocol> delegate; @end
5.在在Student.m文件中
#import "Student.h" @implementation Student -(void)findHourse { NSLog(@"學生要找房子"); //通知代理幫他找房子
if([self.delegate respondsToSelector:@selector(studentFindHourse)]) { [self.delegate studentFindHourse]; } } @end
6.在main文件中
#import <Foundation/Foundation.h> #import "Student.h" #import "Intermediary.h" #import "Intermediary1.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu=[Student new]; Intermediary *inter=[Intermediary new]; stu.delegate=inter; [stu findHourse]; } return 0; }
7.運行結果
2016-03-01 21:26:41.375 代理模式[2672:236249] 學生要找房子 2016-03-01 21:26:41.377 代理模式[2672:236249] -[Intermediary studentFindHourse] 幫學生找房子 Program ended with exit code: 0
代理中,需要記住的關鍵是在發出代理請求的類(A)中聲明代理人(B)的實例變量,這樣就可以保證A 能通過調用B中B代理的方法來完成B代理的事情,即自己代理給B 的事情。