107,Protocol在代理设计模式中应用

来源:互联网 发布:c语言输出水仙花数 编辑:程序博客网 时间:2024/06/06 12:58

StudentProtocol.h:

#import <Foundation/Foundation.h>

//只有具备找房子的代理,才能为学生找房子,所以,让代理遵守该协议

@protocol StudentProtocol <NSObject>


-(void)helpStudentFindHouse;


@end


Student.h:

#import <Foundation/Foundation.h>

#import "LoveHouse.h"

#import "StudentProtocol.h"


@interface Student : NSObject


//使用id接收不同的对象,这样就有很多的扩展性了

@property(nonatomic,strong)id<StudentProtocol> delegate;


-(void)findHouse;


@end


Student.m:

#import "Student.h"


@implementation Student


-(void)findHouse{

    NSLog(@"学生找房子");

    if ([self.delegaterespondsToSelector:@selector(helpStudentFindHouse)]) {

        [self.delegatehelpStudentFindHouse];

    }

}


@end


SameCity.h:

#import <Foundation/Foundation.h>

#import "StudentProtocol.h"


@interface SameCity : NSObject <StudentProtocol>


@end


SameCity.m:

#import "SameCity.h"


@implementation SameCity


-(void)helpStudentFindHouse{

    NSLog(@"SameCity帮学生找房子!");

}


@end


LoveHouse.h:

#import <Foundation/Foundation.h>

#import "StudentProtocol.h"


@interface LoveHouse : NSObject <StudentProtocol>


-(void)helpStudentFindHouse;

@end


LoveHouse.m:

#import "LoveHouse.h"


@implementation LoveHouse


-(void)helpStudentFindHouse{

    NSLog(@"LoveHouse帮学生找房子!");

}


@end


main:


#import <Foundation/Foundation.h>

#import "Student.h"

#import "LoveHouse.h"

#import "SameCity.h"


/*

 使用代理设计模式,帮学生找房子

 */


int main(int argc,const char * argv[]) {

    

    Student *student = [Studentnew];

    LoveHouse *loveHouse = [LoveHousenew];

    student.delegate = loveHouse;

    [student findHouse];

    

    NSLog(@"------------");

    

    //代理人改为【同城】帮忙找房

    SameCity *sameCity = [SameCitynew];

    student.delegate = sameCity;

    [student findHouse];

    return 0;

}

//2015-12-19 11:53:43.470 2,代理设计模式[2058:80563]学生找房子

//2015-12-19 11:53:43.471 2,代理设计模式[2058:80563] LoveHouse帮学生找房子!

//2015-12-19 11:53:43.471 2,代理设计模式[2058:80563] ------------

//2015-12-19 11:53:43.471 2,代理设计模式[2058:80563]学生找房子

//2015-12-19 11:53:43.471 2,代理设计模式[2058:80563] SameCity帮学生找房子!

//Program ended with exit code: 0


main:


0 0