什么是代理设计模式
在开发中往往会遇到这几种情景,可以使用代理模式处理:
1.当A对象想监听B对象的一些变化时。
2. 当B对象发生一些事情, 想通知A对象的时候。
3.当对象A无法处理某些行为的时候,想让对象B帮忙处理(让对象B成为对象A的代理对象。
代理解决对象之间传值
-
找代理三个步骤
1.列出自己不想做或者不能做的事情,制定一个协议,例如买房子需求(@protocol PersonProtocol <NSObject >)
2.定一个代理属性(weak修饰防止循环引用)
@property (nonatomic, weak) id<PersonProtocol> delegate;
3.当自己触发某个事件,就让代理去执行协议方法
[self.delegate personFindHourse:self];招代理的类对应的.h文件代码
#import <Foundation/Foundation.h> @class Person; @protocol PersonProtocol <NSObject> - (void)personFindHourse:(Person *)person; @end
@interface Person : NSObject @property (nonatomic, strong) id<PersonProtocol> delegate; - (void)findHourse; @end
招代理的类对应的.m文件代码
#import "Person.h" @implementation Person - (void)findHourse { if ([self.delegate respondsToSelector:@selector(personFindHourse:)]) { [self.delegate personFindHourse:self]; } } @end
-
做代理遵守的规则
1.遵守代理协议
@interface LinkHome : NSObject <PersonProtocol>
#import <Foundation/Foundation.h> @protocol PersonProtocol; @interface LinkHome : NSObject <PersonProtocol> @end
2.实现代理方法
#import "LinkHome.h" #import "Person.h" @implementation LinkHome - (void)personFindHourse:(Person *)person { NSLog(@"%s", __func__); } @end
3.建立两者联系,找代理的类给代理赋值
Person *p = [Person new]; LinkHome *linkhome = [LinkHome new]; //链家实现了找房协议的方法,所以让链家成为人的代理 p.delegate = linkhome; //人只要调用findHourse方法,代理就会帮人去找房 [p findHourse];