委托模式从GoF装饰(Decorator)模式、适配器(Adapter)模式和模板方法(Template Method)模式等演变而来。委托模式经常设计一个代理对象和一个协议,两者经常一起出现,而协议很类似于Android中的接口,协议其实就是声明一些方法(必须实现方法或者可选实现方法)。
//
// Teacher.h
//
#import <Foundation/Foundation.h>
@protocol TearcherDelegate <NSObject>
@required
- (void)sleep;
- (void)eat;
- (void)work;
@optional
- (void)teach;
@end
@interface Teacher : NSObject
{
NSTimer *myTimer;
int count;
}
@property (nonatomic,retain) id<TearcherDelegate> delegate;
- (void)start;
@end
//
// Teacher.m
//
#import "Teacher.h"
@implementation Teacher
- (void)dealloc
{
[_delegate release];
[super dealloc];
}
- (void)start
{
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(handle) userInfo:nil repeats:YES];
}
- (void)handle
{
switch (count)
{
case 0:
if ([_delegate respondsToSelector:@selector(sleep)])
{
[_delegate sleep];
}
count ++;
break;
case 1:
if ([_delegate respondsToSelector:@selector(eat)])
{
[_delegate eat];
}
count ++;
break;
case 2:
if ([_delegate respondsToSelector:@selector(work)])
{
[_delegate work];
}
[myTimer invalidate];
myTimer = nil;
break;
default:
break;
}
}
实际运用:
- (void)viewDidLoad
{
[super viewDidLoad];
Teacher *teacher = [[Teacher alloc] init];
teacher.delegate = self;
[teacher start];
[teacher release];
}
- (void)sleep
{
NSLog(@"sleep");
}
- (void)eat
{
NSLog(@"eat");
}
- (void)work
{
NSLog(@"work");
}
至此,委托模式介绍已经完毕,程序运行效果如下:
2014-09-06 22:59:10.178 Test002[1777:907] sleep
2014-09-06 22:59:13.108 Test002[1777:907] eat
2014-09-06 22:59:16.169 Test002[1777:907] work