代理模式的原理
一个对象和另一个对象耦合,代理模式是为了降低耦合度
Customer & 使用代理的注意事项
- @class, 提示协议方法有该类的引用
- weak 防止循环引用
- @required or @Optional 要写清楚
Customer
@class Customer;
@protocol CustomerDelegate <NSObject>
@required
- (void)custmer:(Customer *)custmer buyItemCount:(NSInteger)count;
@end
@interface Customer : NSObject
// 经销商
@property (nonatomic, weak) id <CustomerDelegate> delegate;
// 顾客买卖行为
- (void)buyItemCount:(NSInteger)count;
@end
- (void)buyItemCount:(NSInteger)count {
if (self.delegate && [self.delegate respondsToSelector:@selector(custmer:buyItemCount:)]) {
[self.delegate custmer:self buyItemCount:count];
}
}
ViewController
#import "ViewController.h"
#import "Customer.h"
// 经销商
@interface ViewController ()<CustomerDelegate>
- (void)viewDidLoad {
[super viewDidLoad];
Customer *customer = [[Customer alloc] init];
customer.delegate = self;
[customer buyItemCount:5];
}
- (void)custmer:(Customer *)custmer buyItemCount:(NSInteger)count {
NSLog(@"%ld", (long)count);
}
使用场景:用于类与类之间的值传递
Customer设定消息接受方的遵循条件
@required
- (void)custmer:(Customer *)custmer buyItemCount:(NSInteger)count;
@end
@interface Customer : NSObject
// 经销商
@property (nonatomic, weak) id <CustomerDelegate> delegate;
Customer发送消息
- (void)buyItemCount:(NSInteger)count {
//代理存在,并且代理能响应这个方法
if (self.delegate && [self.delegate respondsToSelector:@selector(custmer:buyItemCount:)]) {
[self.delegate custmer:self buyItemCount:count];
}
}
ViewController准备接收
@interface ViewController ()<CustomerDelegate>
ViewController获得所传递的消息
Customer *customer = [[Customer alloc] init];
customer.delegate = self;
[customer buyItemCount:5];
}
- (void)custmer:(Customer *)custmer buyItemCount:(NSInteger)count {
NSLog(@"%ld", (long)count);
}
代理使用验证
//代理存在,并且代理能响应这个方法
if (self.delegate && [self.delegate respondsToSelector:@selector(custmer:buyItemCount:)]) {
[self.delegate custmer:self buyItemCount:count];
}
协议使用场景
约束对象,筛选对象。比如传递的对象,必须实现某种方法
协议
@protocol TCPProtocol <NSObject>
@required
// 获取源端口号
- (NSInteger)sourcePort;
// 获取目的地端口号
- (NSInteger)destinationPort;
@end
遵循协议的类
@interface Model : NSObject <TCPProtocol>
// 获取源端口号
- (NSInteger)sourcePort {
return 10;
}
// 获取目的地端口号
- (NSInteger)destinationPort {
return 20;
}
传递遵循协议的对象
- (void)accessTCPData:(id <TCPProtocol>)data {
self.sourcePort = [data sourcePort];
self.destinationPort = [data destinationPort];
}