黑马程序员--protocol代理模式

来源:互联网 发布:蔬菜交易软件 编辑:程序博客网 时间:2024/05/01 03:11

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

利用协议实现代理模式的主要思路:

1)定义一个协议,里面声明代理类需要实现的方法列表。

2)创建一个代理类,遵守上面的代理协议

3)在需要代理的类中,定义一个对象, 类型为id,且遵守代理协议的成员变量(delegate)。

4)在主类中调用成员变量delegate的方法,调用代理类的方法。

5)main.m或其他使用主类的文件中,为主类的成员变量赋值。


应用:学生通过中介找房子


findHouseProtocol.h   //协议

#import <Foundation/Foundation.h>@protocol findHouseProtocol <NSObject>-(void)findHouse;@end


Student.h

#import <Foundation/Foundation.h>#import "findHouseProtocol.h"@interface Student : NSObject-(void)needHouse;@property(nonatomic,strong)id<findHouseProtocol> delegate;@end


Student.m

#import "Student.h"@implementation Student-(void)needHouse{        NSLog(@"学生需要一个房子");    [self.delegate findHouse];}@end


linkHome.h

#import <Foundation/Foundation.h>#import "findHouseProtocol.h"@interface linkHome : NSObject<findHouseProtocol>@end


linkHome.m

#import "linkHome.h"@implementation linkHome-(void)findHouse{    NSLog(@"链家房产正在寻找房子。");    NSLog(@"链家房产找到房子。");}@end


main.m

#import <Foundation/Foundation.h>#import "Student.h"#import "linkHome.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        Student *stu = [Student new];        //代理的类        linkHome *link = [linkHome new];                stu.delegate = link;        [stu needHouse];         }    return 0;}


0 0
原创粉丝点击