简单的房屋销售委托例子

#import <Foundation/Foundation.h>

@protocol SaleHouse <NSObject>//协议头文件

-(void)saleHouse;

@end


#import <Foundation/Foundation.h>

#import "SaleHouse.h"//卖房者声明部分,遵循卖房协议

@interface HouseSaler : NSObject<SaleHouse>

@property(retain,nonatomic) NSString *name;

@property(assign,nonatomic) int age;

+(id)houseSalerWithName:(NSString *) n andAge:(int) a;

-(void)saleHouse;

@end


#import "HouseSaler.h"//卖房者实现部分

@implementation HouseSaler

+(id)houseSalerWithName:(NSString *) n andAge:(int) a{

HouseSaler *h = [HouseSalernew];

   h.name = n;

   h.age = a;

return [h autorelease];

}

-(void)saleHouse{

NSLog(@"我是房屋销售%@,%d,正在努力帮房东卖房子",self.name,self.age);

}

@end


#import <Foundation/Foundation.h>

#import "SaleHouse.h"

@interface Landlord : NSObject//房东声明部分

@property(retain,nonatomic) NSString *name;

@property(assign,nonatomic) int age;

+(id)landLordWithName:(NSString *) n andAge:(int) a;

@property(assign,nonatomic) id<SaleHouse>deleagte;//设置代理

-(void)shouqian;

@end


#import "Landlord.h"//房东实现部分

@implementation Landlord

+(id)landLordWithName:(NSString *) n andAge:(int) a{

Landlord *l = [Landlordnew];

   l.name = n;

   l.age = a;

return [l autorelease];

}

-(void)shouqian{

if ([self.deleagteconformsToProtocol:@protocol(SaleHouse)]) {

if ([self.deleagterespondsToSelector:@selector(saleHouse)]) {

           [self.deleagtesaleHouse];

       }

   }

NSLog(@"我是房东%@,%d,正在等着收钱",self.name,self.age);

}

@end


#import <Foundation/Foundation.h>

#import "HouseSaler.h"

#import "Landlord.h"

int main(int argc, constchar * argv[])//main函数测试

{

@autoreleasepool {

HouseSaler *h = [HouseSalerhouseSalerWithName:@"小麦"andAge:23];

Landlord *l = [LandlordlandLordWithName:@"小明"andAge:30];

       l.deleagte = h;//指定代理

       [l shouqian];

   }

return 0;

}