一·什么事代理模式?设计模式
代理模式是在oc中常常遇到的一种设计模式,那什么叫作代理模式呢? 举个例子:有一租客, 他要租房子,但是他不知道哪儿有房子可租,因而他就找了中介,让中介去帮他找房子,因而他和中介之间商定了一个协议,协议中写明了中介须要作的事情是帮他找房子, 而中介就成为了租客的代理人, 即:他和中介之间有个协议,中介继承该协议,因而中介就须要实现该协议中的条款成为代理人。atom
1 #import <Foundation/Foundation.h> 2 3 @protocol StudentProtocol <NSObject> 4 /* 5 协议要作的事儿 6 帮学生找房子 7 */ 8 -(void)studentFindHourse; 9 @end
2,再次声明Intermediary(中介)类,即代理的人:spa
在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类code
在Student.h文件中blog
#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文件中it
#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.运行结果io
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 的事情。