iOS设计模式:代理
2017-03-03 本文已影响27人
younger_times
![](https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488524422690&di=208cc610f7ca68daa755fac75bb645f8&imgtype=0&src=http://images.cnblogs.com/cnblogs_com/oneword/WindowsLiveWriter/b14b46cfb268_CE6E/image.png)
视频教程-极客学院
ps:感觉打的一手好广告啊,因为自己不太爱看视频,但这类又必须看才能明白。粘贴源代码是为了以后查阅方便,也注释了自己的理解。
代理
Customer
#import <Foundation/Foundation.h>
@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
#import "Customer.h"
@implementation Customer
- (void)buyItemCount:(NSInteger)count {
if (self.delegate && [self.delegate respondsToSelector:@selector(custmer:buyItemCount:)]) {
[self.delegate custmer:self buyItemCount:count];
}
}
@end
使用
#import "ViewController.h"
#import "Customer.h"
// 经销商
@interface ViewController () <CustomerDelegate>
@end
@implementation ViewController
- (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);
}
@end
协议
感觉协议和代理是有所不同,但不同...感觉说不出来
TCPProtocol
#import <Foundation/Foundation.h>
@protocol TCPProtocol <NSObject>
@required
// 获取源端口号
- (NSInteger)sourcePort;
// 获取目的地端口号
- (NSInteger)destinationPort;
@end
Model
#import <Foundation/Foundation.h>
#import "TCPProtocol.h"
@interface Model : NSObject <TCPProtocol>
@end
#import "Model.h"
@implementation Model
// 获取源端口号
- (NSInteger)sourcePort {
return 10;
}
// 获取目的地端口号
- (NSInteger)destinationPort {
return 20;
}
@end
使用
#import "ViewController.h"
#import "Customer.h"
#import "TCPProtocol.h"
// 经销商
@interface ViewController ()
@property (nonatomic) NSInteger sourcePort;
@property (nonatomic) NSInteger destinationPort;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)accessTCPData:(id <TCPProtocol>)data {
self.sourcePort = [data sourcePort];
self.destinationPort = [data destinationPort];
}