传入的对象,代替当前类完成了某个功能,称为代理模式
@protocol ClassNameDelegate<NSObject> -(void)functionName; @end
ClassName 需要其他类实现的功能,都声明在同一个协议中。
@interface ClassName:NSObject //设置代理属性 @property (nonatomic,strong)id<ClassNameDelegate>delegate; @end
类说明:Doctor Sick
协议:SickDelegate
#import <Foundation/Foundation.h> @protocol SickDelegate <NSObject> @required -(void)cure; @end
===类声明===
#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
===类实现===
#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...
原文:http://my.oschina.net/u/1032974/blog/345375