在ViewController文件里
#import "ViewController.h"
#import "HouseSaler.h"
#import "Landlord.h"
#import "Landlord_Protocol.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
委托模式
两个对象间不能够直接联系,需要通过一个第三方对象帮助他们联系,这一种模式,我们称为'委托模式'
如何在OC中使用委托模式?在OC中实现委托模式需要OC中的一个元素'protocol',即协议
*/
HouseSaler *saler = [HouseSaler new];
Landlord *landlord = [Landlord new];
landlord.delegate = saler;
saler.customer = landlord;
[landlord registerHouse];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
在HouseSaler.h文件里
#import <Foundation/Foundation.h>
#import "Landlord_Protocol.h"
#import "Landlord.h"
@interface HouseSaler : NSObject<Landlord_Protocol>
@property(nonatomic,assign)Landlord *customer;
-(void)saleHouse;
@end
在HouseSaler.m文件里
#import "HouseSaler.h"
@implementation HouseSaler
-(void)saleHouse
{
NSLog(@"我是中介,我替卖家卖房子");
}
//实现协议里卖房子的方法
-(void)mustSaleHouse
{
NSLog(@"我是中介,我与房东签了协议,我必须要卖出房子");
}
-(void)payMoney
{
NSLog(@"我是中介,我卖房子了,钱我给你了");
[self.customer receiveMoney];
}
@end
在Landlord.h文件里
#import <Foundation/Foundation.h>
//#import "HouseSaler.h"
#import "Landlord_Protocol.h"
@interface Landlord : NSObject
//1.这是最简单的委托模式
//这里使用assign是为了防止循环引用
//@property(nonatomic,assign)HouseSaler *delegate;
//使用正式协议的委托模式
@property(nonatomic,assign)id<Landlord_Protocol>delegate;
-(void)registerHouse;
//用于表示房东收到钱了
-(void)receiveMoney;
@end
在Landlord.m文件里
#import "Landlord.h"
@implementation Landlord
-(void)registerHouse
{
NSLog(@"我是房东,我已经将房子登记到中介了");
if (self.delegate && [self.delegate conformsToProtocol:@protocol(Landlord_Protocol)])
{
[self.delegate mustSaleHouse];
[self.delegate payMoney];
}
}
-(void)receiveMoney
{
NSLog(@"我是房东,我收到钱了");
}
@end
在Landlord_Protocol.h文件里
#import <Foundation/Foundation.h>
@protocol Landlord_Protocol <NSObject>
@required
-(void)mustSaleHouse;
-(void)payMoney;
@end