委托模式
定义:两个对象间不能够直接联系,需要通过一个第三方对象,帮助它们联系,这样一种模式,我们称之为委托模式。
如何在OC中使用委托模式?在OC中实现委托模式需要了解OC中的一个元素’protocol’,即’协议’。
协议
定义:协议是一套标准,定义了应该实现什么,但不关心具体的怎么实现。
OC的协议是由’@protocol’声明的一组方法列表。
@required //代表以下方法是必须实现的方法,默认是必须实现的方法
-(void)teacherLateMoney:(int)money;
-(void)studentLateMoney:(int)money;
@optional//代表以下方法是可选择实现方法
-(void)sayHi;
确认协议的实现:
#import <Foundation/Foundation.h>
#import "StudentWithTeacher.h"
@interface Teacher : NSObject <StudentWithTeacher>;
@end
#import "Teacher.h"
@implementation Teacher
#pragma mark StudentWithTeacher
-(void)teacherLateMoney:(int)money{
NSLog(@"%d",money);
}
-(void)studentLateMoney:(int)money{
NSLog(@"%d",money);
}
@end