黑马程序员技术交流社区

标题: 代理设计模式的一个小应用 [打印本页]

作者: twototwoto    时间: 2016-7-25 00:56
标题: 代理设计模式的一个小应用
//利用协议实现代理模式的主要思路是:
//1)定义一个协议,里面声明代理类需要实现的方法列表,比如这里一个代理类需要实现speechForTeacher方法
//(2)创建一个代理类(Student)遵守上边的代理协议
//(3)在需要代理的类中(Teacher)定义一个对象,类型为id且遵守代理协议的成员变量(delegate)
// 4)在Teacher类中调用成员变量delegate(代理)的方法,调用代理类的方法。
// (5)main.m或其他使用Teacher类的文件中,为Teacher类的成员变量(代理类)赋值


main.m
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Teacher.h"
#import "speechProtocol.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Teacher *teacher = [Teacher new];
        Student *student = [Student new];
// (5)main.m或其他使用Teacher类的文件中,为Teacher类的成员变量(代理类)赋值,
        teacher.delegate = student;
        [teacher speech];
        //代理类:LinkHome
        //代理对象:delegate
        //协议:speechProtocol
        //协议的内容:speechForTeacher
    }
    return 0;
}


//Students.h
#import <Foundation/Foundation.h>
#import "speechProtocol.h"
//(2)创建一个代理类(Student)遵守上边的代理协议
@interface Student : NSObject<speechProtocol>
@end


//Students.m
#import "Student.h"
#import "speechProtocol.h"
@implementation Student
-(void)speechForTeacher{
    NSLog(@"老师有事,我来代替老师来做个演讲");
}
@end


//Teacher.h
#import <Foundation/Foundation.h>
#import "speechProtocol.h"
@interface Teacher : NSObject
//(3)在需要代理的类中(Teacher)定义一个对象,类型为id且遵守代理协议的成员变量(delegate)
@property (nonatomic,strong) id<speechProtocol> delegate;
-(void)speech;

@end


//Teacher.m
#import "Teacher.h"

@implementation Teacher
-(void)speech{
    NSLog(@"教师需要自己做一个演讲,但是该老师现在有事");
//    (4)在Teacher类中调用成员变量delegate(代理)的方法,调用代理类的方法。
    [self.delegate speechForTeacher];

}
@end


//speechProtocol.h
#import <Foundation/Foundation.h>
//1)定义一个协议,里面声明代理类需要实现的方法列表,比如这里一个代理类需要实现speechForTeacher方法
@protocol speechProtocol <NSObject>
-(void)speechForTeacher;
@end


如果有错误,请指正
既然都你来了,留下脚印再走吧{:3_53:}

作者: gdutyong    时间: 2016-7-25 01:23
一般代理方法实现要传个参数,等到调用的时候,Teacher就把自己传进去,例如 [self.delegate speechForTeacher:self];





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2