ios-使用委托模式(代理模式)

委托模式从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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值