一 代理模式概念
传入的对象,代替当前类完成了某个功能,称为代理模式
二 代理模式规范
1.协议名的规范
@protocol ClassNameDelegate<NSObject>
-(void)functionName;
@end
ClassName 需要其他类实现的功能,都声明在同一个协议中。
2.类声明的规范
@interface ClassName:NSObject
//设置代理属性
@property (nonatomic,strong)id<ClassNameDelegate>delegate;
@end
三 代码
类说明:Doctor Sick
协议:SickDelegate
1.SickDelegate
#import <Foundation/Foundation.h>
@protocol SickDelegate <NSObject>
@required
-(void)cure;
@end
2.Doctor
===类声明===
#import <Foundation/Foundation.h>
#import "SickDelegate.h"
@interface Doctor : NSObject<SickDelegate>
@property(nonatomic,strong)NSString *name;
@end
===类实现===
#import "Doctor.h"
@implementation Doctor
/**
* 实现协议方法
*/
-(void)cure
{
NSLog(@"%@ sure...", self.name);
}
@end
3.Sick
===类实现===
#import <Foundation/Foundation.h>
#import "SickDelegate.h"
@interface Sick : NSObject
/**
* 属性
*/
@property (nonatomic, strong) NSString *name;
/**
* 代理
*/
@property (nonatomic, strong)id<SickDelegate> delegate;
/**
* 生病
*/
-(void)ill;
@end
===类声明===
#import "Sick.h"
@implementation Sick
/**
* 生病
*/
-(void)ill
{
//通过代理调用 看病 方法
[self.delegate cure];
}
@end
四.主函数
#import <Foundation/Foundation.h>
#import "Doctor.h"
#import "Sick.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
/**
* 患者类
*/
Sick *joker = [Sick new];
joker.name=@"joker";
/**
* 医生类
*/
Doctor *rose = [Doctor new];
rose.name=@"rose";
//绑定代理 让rose 为 joker 看病
joker.delegate=rose;
[joker ill];
}
return 0;
}
===输出===
2014-11-16 23:42:11.736 代理模式[1209:303] rose sure...